@codeyam/codeyam-cli 0.1.0-staging.eb21b2f → 0.1.0-staging.fef152f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +13 -13
  4. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +232 -5
  5. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  6. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  7. package/analyzer-template/packages/aws/package.json +10 -10
  8. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  9. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +6 -2
  10. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  11. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +14 -2
  12. package/analyzer-template/project/constructMockCode.ts +32 -5
  13. package/analyzer-template/project/orchestrateCapture.ts +4 -1
  14. package/analyzer-template/project/writeScenarioComponents.ts +62 -12
  15. package/background/src/lib/virtualized/project/constructMockCode.js +28 -5
  16. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  17. package/background/src/lib/virtualized/project/orchestrateCapture.js +4 -1
  18. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  19. package/background/src/lib/virtualized/project/writeScenarioComponents.js +46 -7
  20. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  21. package/codeyam-cli/src/cli.js +31 -20
  22. package/codeyam-cli/src/cli.js.map +1 -1
  23. package/codeyam-cli/src/commands/memory.js +3 -56
  24. package/codeyam-cli/src/commands/memory.js.map +1 -1
  25. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +6 -0
  26. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -1
  27. package/codeyam-cli/src/utils/npmVersionCheck.js +2 -2
  28. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -1
  29. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +1 -1
  30. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -1
  31. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +0 -1
  32. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -1
  33. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +2 -4
  34. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -1
  35. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +84 -0
  36. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  37. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +83 -0
  38. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  39. package/codeyam-cli/src/utils/rules/index.js +1 -0
  40. package/codeyam-cli/src/utils/rules/index.js.map +1 -1
  41. package/codeyam-cli/src/utils/rules/pathMatcher.js +10 -0
  42. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -1
  43. package/codeyam-cli/src/utils/rules/sourceFiles.js +47 -0
  44. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  45. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  46. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  47. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  48. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  49. package/codeyam-cli/src/utils/versionInfo.js +21 -0
  50. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  51. package/codeyam-cli/src/webserver/build/client/assets/globals-Dzl-jeq-.css +1 -0
  52. package/codeyam-cli/src/webserver/build/client/assets/labs-DAvt-sy-.js +1 -0
  53. package/codeyam-cli/src/webserver/build/client/assets/{manifest-390cb8fa.js → manifest-2d0e2ebb.js} +1 -1
  54. package/codeyam-cli/src/webserver/build/client/assets/memory-DVGtTawo.js +92 -0
  55. package/codeyam-cli/src/webserver/build/client/assets/root-Bg3WICdl.js +62 -0
  56. package/codeyam-cli/src/webserver/build/server/assets/{index-CXfuiwt3.js → index-CpreP2n8.js} +1 -1
  57. package/codeyam-cli/src/webserver/build/server/assets/server-build-DyvoFrHR.js +273 -0
  58. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  59. package/codeyam-cli/src/webserver/build-info.json +5 -5
  60. package/package.json +5 -5
  61. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +213 -3
  62. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  63. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  64. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  65. package/packages/utils/src/lib/fs/rsyncCopy.js +6 -2
  66. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  67. package/codeyam-cli/src/webserver/build/client/assets/globals-CCgBKWy4.css +0 -1
  68. package/codeyam-cli/src/webserver/build/client/assets/labs-BK0C1H1T.js +0 -1
  69. package/codeyam-cli/src/webserver/build/client/assets/memory-CzZySbBE.js +0 -78
  70. package/codeyam-cli/src/webserver/build/client/assets/root-DnbDhvTU.js +0 -62
  71. package/codeyam-cli/src/webserver/build/server/assets/server-build-BSvme_Ao.js +0 -259
@@ -1,259 +0,0 @@
1
- var bi=Object.defineProperty;var Wa=e=>{throw TypeError(e)};var vi=(e,t,r)=>t in e?bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var gn=(e,t,r)=>vi(e,typeof t!="symbol"?t+"":t,r),wi=(e,t,r)=>t.has(e)||Wa("Cannot "+r);var Ha=(e,t,r)=>(wi(e,t,"read from private field"),r?r.call(e):t.get(e)),Va=(e,t,r)=>t.has(e)?Wa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as he}from"react/jsx-runtime";import{PassThrough as Ci}from"node:stream";import{createReadableStreamFromReadable as Ni}from"@react-router/node";import{ServerRouter as Si,useFetcher as Ae,useLocation as Jn,useNavigate as Tt,Link as se,UNSAFE_withComponentProps as De,Meta as Ei,Links as Ai,ScrollRestoration as ki,Scripts as Pi,useLoaderData as Be,useRevalidator as ot,Outlet as _i,data as B,useSearchParams as on,useRouteLoaderData as Mi,useParams as Fs,useActionData as Ti,redirect as ji}from"react-router";import{isbot as Ii}from"isbot";import{renderToPipeableStream as $i}from"react-dom/server";import{useState as P,useEffect as ee,useCallback as oe,createContext as Vr,useContext as Gn,useRef as Ne,useMemo as re}from"react";import{Settings as Ja,CheckCircle2 as Jr,Bug as Os,AlertTriangle as Tn,Check as kt,Copy as Rt,Loader2 as Ze,HomeIcon as Ri,GitCommitIcon as Ga,File as Di,RefreshCw as Li,BookOpen as Gr,FlaskConical as Fi,SettingsIcon as Oi,PanelsTopLeftIcon as zi,ComponentIcon as Yi,FileText as qa,Code as Ka,Box as Bi,List as Ui,BarChart3 as Wi,Tag as Hi,Image as tn,Code2 as zs,Activity as br,ChevronDown as st,CircleEqual as Vi,ArrowLeft as Ji,Terminal as jn,Search as ln,ChevronRight as jt,Save as Gi,MessageSquare as qi,Pause as Ys,ListTodo as Ki,PauseCircle as Qi,FileCode as In,GripVertical as Zi,Ban as Xi,CheckCircle as el,FolderOpen as tl,CodeXml as nl,Zap as rl,Pencil as al,Trash2 as sl,X as qr,Folder as Bs,Info as Lr,Plus as Kr,Eye as ol,FolderTree as il,ChevronsUpDown as Us,ChevronsDownUp as Ws}from"lucide-react";import"fetch-retry";import ll from"better-sqlite3";import{Pool as cl}from"pg";import*as K from"fs";import Pt,{existsSync as rt,readdirSync as dl,rmSync as vr}from"fs";import*as Z from"path";import ie,{join as Qa}from"path";import{OperationNodeTransformer as ul,Kysely as Hs,ParseJSONResultsPlugin as hl,SqliteDialect as ml,PostgresDialect as pl,sql as Ke}from"kysely";import*as fl from"kysely/helpers/sqlite";import*as gl from"kysely/helpers/postgres";import je from"typescript";import*as Re from"fs/promises";import fe,{readdir as Za,stat as Xa,readFile as nn,writeFile as qt,mkdir as yl}from"fs/promises";import*as xl from"os";import Fr from"os";import bl from"prompts";import $n from"chalk";import*as vl from"crypto";import qn,{randomUUID as Vs,createHmac as wl}from"crypto";import{execSync as Me,spawn as Kn,exec as Qr}from"child_process";import{fileURLToPath as Qn}from"url";import{promisify as Zr}from"util";import Cl from"dotenv";import Nl,{EventEmitter as Sl}from"events";import{v4 as El}from"uuid";import Al from"openai";import kl from"p-queue";import es from"p-retry";import{DynamoDBClient as Zn,PutItemCommand as Pl}from"@aws-sdk/client-dynamodb";import{LRUCache as Xr}from"lru-cache";import"pluralize";import"piscina";import _l from"json5";import{marshall as Ml}from"@aws-sdk/util-dynamodb";import Tl from"v8";import{Prism as jl}from"react-syntax-highlighter";import{vscDarkPlus as Il}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as $l}from"node:crypto";import{minimatch as Js}from"minimatch";import Rl from"react-markdown";import Dl from"remark-gfm";import Ll from"react-diff-viewer-continued";const Gs=5e3;function Fl(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),h=d&&Ii(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>m(),Gs+1e3);const{pipe:p,abort:m}=$i(n(Si,{context:a,url:e.url}),{[h](){c=!0;const f=new Ci({final(g){clearTimeout(u),u=void 0,g()}}),y=Ni(f);r.set("Content-Type","text/html"),p(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const Ol=Object.freeze(Object.defineProperty({__proto__:null,default:Fl,streamTimeout:Gs},Symbol.toStringTag,{value:"Module"}));function zl({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=P(!1);ee(()=>{i(!0)},[]);const c=oe(()=>{r==null||r(e)},[r,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
- ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
- `,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&a}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:s})]})}const qs="/assets/cy-logo-cli-CCKUIm0S.svg";function Yl(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 Bl({content:e,className:t=""}){const[r,a]=P(!1),s=oe(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:s,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(he,{children:[n(kt,{size:14}),"Copied"]}):l(he,{children:[n(Rt,{size:14}),"Copy"]})})}function Ks({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=P(""),[c,d]=P(a),[h,u]=P(!1),[p,m]=P(!1),[f,y]=P(null),[g,x]=P(null),v=Ae(),b=v.state!=="idle",C=!!(r.scenarioId||r.analysisId),N=r.analysisId||r.scenarioId||"",k=()=>{const I=`/codeyam-diagnose ${N}`;return o.trim()?`${I} ${o.trim()}`:I};if(v.data&&!p&&!g){const I=v.data;I.success&&I.reportId?(m(!0),y(I.reportId)):I.error&&x(I.error)}const w=async()=>{x(null);const I=new FormData;if(I.append("issueType","other"),I.append("description",o),I.append("email",c),I.append("source",r.source),I.append("entitySha",r.entitySha||""),I.append("scenarioId",r.scenarioId||""),I.append("analysisId",r.analysisId||""),I.append("currentUrl",r.currentUrl),I.append("entityName",r.entityName||""),I.append("entityType",r.entityType||""),I.append("scenarioName",r.scenarioName||""),I.append("errorMessage",r.errorMessage||""),s)try{const L=await(await fetch(s)).blob();I.append("screenshot",L,"screenshot.jpg")}catch(D){console.error("Failed to convert screenshot:",D)}v.submit(I,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},A=()=>{i(""),u(!1),m(!1),y(null),x(null),t()},M=I=>{I.key==="Escape"&&A()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:M,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?n("div",{className:"animate-spin",children:n(Ja,{size:24,style:{strokeWidth:1.5}})}):p?n(Jr,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Os,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:p?"Report Submitted":"Report Issue"})]}),n("button",{onClick:A,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),p?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick: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:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:Yl(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&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:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),s&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:I=>i(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"})]}),C&&l(he,{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:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:k()}),n(Bl,{content:k(),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:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:C?"opacity-75":"",children:[C&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:I=>d(I.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:[n(Tn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.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:[n(Tn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("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"}),n("button",{onClick:()=>void w(),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(he,{children:[n("div",{className:"animate-spin",children:n(Ja,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const ts={source:"navbar"},ea=Vr(void 0);function Ul({children:e}){const[t,r]=P(ts),a=oe(o=>{r(o)},[]),s=oe(()=>{r(ts)},[]);return n(ea.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function Xe(e){const t=Gn(ea),r=Ne(t);ee(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function Wl(){const e=Gn(ea),t=Jn();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function Hl({labs:e,isAdmin:t}){var k;const r=Jn(),a=Tt(),[s,o]=P(),[i,c]=P(!1),[d,h]=P(!1),[u,p]=P(null),m=Ae();ee(()=>{m.state==="idle"&&!m.data&&m.load("/api/generate-report")},[m]);const f=((k=m.data)==null?void 0:k.defaultEmail)||"",y={width:"20px",height:"20px",strokeWidth:1.5},g=(e==null?void 0:e.simulations)??!1,x=[{id:"dashboard",icon:n(Ri,{style:y}),link:"/",name:"Dashboard",hidden:!g},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:y,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!g},{id:"git",icon:n(Ga,{style:y}),link:"/git",name:"Git",hidden:!g},{id:"files",icon:n(Di,{style:y}),link:"/files",name:"Files",hidden:!g},{id:"activity",icon:n(Li,{style:y}),link:"/activity",name:"Activity",hidden:!g},{id:"memory",icon:n(Gr,{style:y}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Fi,{style:y}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Oi,{style:y}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ga,{style:y}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(zi,{style:y}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Yi,{style:y}),link:"/components",name:"Components",hidden:!0}],v=oe(w=>{const A=x.find(M=>M.id===w);A!=null&&A.link&&a(A.link),o(M=>M===w?void 0:w)},[x,a]);ee(()=>{const w={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[A,M]of Object.entries(w))if(M.some(I=>I==="/"?r.pathname==="/":r.pathname.includes(I))){o(A);return}o(void 0)},[r]);const b=async()=>{h(!0);try{const{default:w}=await import("html2canvas-pro"),M=(await w(document.body)).toDataURL("image/jpeg",.8);p(M),c(!0)}catch(w){console.error("Screenshot capture failed:",w),c(!0)}finally{h(!1)}},C=()=>{c(!1),p(null)},N=Wl();return l(he,{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:[n("div",{className:"py-3 mt-2 mb-4",children:n(se,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:qs,alt:"CodeYam",className:"h-6"})})}),x.filter(w=>!w.hidden).map(w=>n(zl,{id:w.id,selected:w.id===s,onClick:v,icon:w.icon,name:w.name},`sidebar-button-${w.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void b(),disabled:d,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:d?n(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Os,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:d?"Capturing...":`Report
6
- Bug`})]})})]}),i&&n(Ks,{isOpen:!0,onClose:C,context:N,defaultEmail:f,screenshotDataUrl:u??void 0})]})}const Qs=Vr(void 0);function Vl({children:e}){const[t,r]=P([]),a=oe((o,i="info",c=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,h])},[]),s=oe(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(Qs.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function ta(){const e=Gn(Qs);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Jl({toast:e,onClose:t}){ee(()=>{const s=e.duration||5e3;if(s>0){const o=setTimeout(()=>{t(e.id)},s);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={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:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Gl({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
- @keyframes slideIn {
8
- from {
9
- transform: translateX(400px);
10
- opacity: 0;
11
- }
12
- to {
13
- transform: translateX(0);
14
- opacity: 1;
15
- }
16
- }
17
- `}),e.map(r=>n(Jl,{toast:r,onClose:t},r.id))]})}function gt(e,t){const[r,a]=P(""),[s,o]=P(!1),[i,c]=P(null),[d,h]=P(!1);ee(()=>{t&&(h(!1),o(!1),c(null))},[t]),ee(()=>{if(!e||!t){t||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){o(!1),h(!1),c(null),a("");return}const x=g.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];a(b.replace(/.*CodeYam Log Level 1: /,""))}const v=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),h(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};p().catch(()=>{});const m=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(m)},[e,t]);const u=oe(()=>{a(""),o(!1),c(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function pt({projectSlug:e,onClose:t}){const[r,a]=P("Loading logs..."),[s,o]=P(!0),[i,c]=P(!0),[d,h]=P("all"),u=Ne(null);return ee(()=>{const p=async()=>{try{const m=await fetch(`/api/logs/${e}`);if(m.ok){const f=await m.text();if(d==="all")a(f);else{const y=f.trim().split(`
19
- `).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});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: ${m.status} - ${await m.text()}`)}catch(m){a(`Error fetching logs: ${m.message}`)}};if(p().catch(()=>{}),s){const m=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(m)}},[e,s,i,d]),ee(()=>{const p=m=>{m.key==="Escape"&&t()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,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:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:p=>h(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:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:p=>o(p.target.checked),className:"cursor-pointer"}),n("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:[n("input",{type:"checkbox",checked:i,onChange:p=>c(p.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function Ve({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},a=r[e]||r.other,s=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(zs,{size:s,color:a.iconColor});case"visual":return n(tn,{size:s,color:a.iconColor});case"type":return n(Hi,{size:s,color:a.iconColor});case"data":return n(Wi,{size:s,color:a.iconColor});case"index":return n(Ui,{size:s,color:a.iconColor});case"functionCall":return n(Ka,{size:s,color:a.iconColor});case"class":return n(Bi,{size:s,color:a.iconColor});case"method":return n(Ka,{size:s,color:a.iconColor});case"other":return n(qa,{size:s,color:a.iconColor});default:return n(qa,{size:s,color:a.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Zs({filePath:e,maxLength:t=60,className:r,style:a}){const o=((c,d)=>{if(c.length<=d)return c;const h="...",u=d-h.length,p=Math.ceil(u*.4),m=Math.floor(u*.6),f=c.slice(0,p),y=c.slice(-m),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>p*.5?f.slice(0,g+1):f,b=x!==-1&&x<m*.5?y.slice(x):y;return`${v}${h}${b}`})(e,t),i=o!==e;return n("span",{className:r||"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:o})}function wr({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(Ve,{type:e.entityType||"other"}),l(se,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,s&&o>0&&` (${o})`]}),n(Zs,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Cr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function ql({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var J,U,Y;const[d,h]=P(!1),[u,p]=P(!1),[m,f]=P(null),[y,g]=P(new Set),[x,v]=P(new Set),[b,C]=P(!1),N=!!i||o.length>0,k=!!i,w=(i==null?void 0:i.entities)||r,A=!!(e!=null&&e.analysisCompletedAt),M=(e==null?void 0:e.readyToBeCaptured)??0,I=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||A&&(M===0||I>=M);const D=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,L=N,{lastLine:_}=gt(t,L),S=k||o.length>0,T=new Set(((J=i==null?void 0:i.entities)==null?void 0:J.map(z=>z.sha))||[]),F=c.filter(z=>!(z.currentEntityShas||[]).some(E=>T.has(E))),q=(()=>{const $=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&D){const E=e.analysisCompletedAt||e.createdAt;if(new Date(E).getTime()>$)return!0}if(F.length>0){const E=F[0],W=E.analysisCompletedAt||E.archivedAt||E.createdAt;if(W&&new Date(W).getTime()>$)return!0}return!1})();return ee(()=>{const z=(i==null?void 0:i.id)||null;N&&!u&&z!==m&&p(!0),!N&&m!==null&&f(null)},[N,i==null?void 0:i.id,u,m]),l(he,{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:[S?n(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(br,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:S?"Analyzing...":"Activity: No Activity Yet"}),S&&n("button",{onClick:z=>{z.stopPropagation(),h(!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:[S?n(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(br,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:S?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{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:n(st,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[S&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(br,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:w.length>0?l("div",{className:"space-y-1.5",children:[(b?w:w.slice(0,3)).map(z=>n(wr,{entity:z,nameSize:"11px",pathSize:"10px",pathMaxLength:150},z.sha)),w.length>3&&n("button",{onClick:()=>C(z=>!z),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Cr,"aria-label":b?"Show fewer entities":`Show ${w.length-3} more entities`,children:b?"Show less":`+${w.length-3} more`}),_&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:_})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((z,$)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:z},$)),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"," ",((U=i.entityShas)==null?void 0:U.length)||0," ",((Y=i.entityShas)==null?void 0:Y.length)===1?"entity":"entities","..."]}),_&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:_})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Vi,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(z=>{var W,H;const $=y.has(z.id),E=$?z.entities:z.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:z.entities.length>0?l("div",{className:"space-y-1.5",children:[E.map(V=>n(wr,{entity:V,nameSize:"10px",pathSize:"9px",pathMaxLength:120},V.sha)),z.entities.length>3&&n("button",{onClick:()=>{g(V=>{const ae=new Set(V);return ae.has(z.id)?ae.delete(z.id):ae.add(z.id),ae})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Cr,"aria-label":$?"Show fewer entities":`Show ${z.entities.length-3} more entities`,children:$?"Show less":`+${z.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[z.type==="analysis"&&n(he,{children:z.entityNames&&z.entityNames.length>0?l("div",{className:"space-y-0.5",children:[z.entityNames.slice(0,5).map((V,ae)=>n("div",{children:V},ae)),z.entityNames.length>5&&l("div",{className:"italic",children:["+",z.entityNames.length-5," more"]})]}):`Analyzing ${((W=z.entityShas)==null?void 0:W.length)||0} ${((H=z.entityShas)==null?void 0:H.length)===1?"entity":"entities"}`}),z.type==="recapture"&&"Recapturing scenario",z.type==="debug-setup"&&"Setting up debug environment"]})},z.id)})})]}),q&&F.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Jr,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:F.slice(0,3).map((z,$)=>{const E=z.entities||[],W=z.analysisCompletedAt||z.archivedAt||z.createdAt||"",H=(()=>{if(!W)return"";const j=Date.now()-new Date(W).getTime(),R=Math.floor(j/6e4),G=Math.floor(j/36e5);return G>0?`${G}h ago`:R>0?`${R}m ago`:"just now"})(),V=x.has($),O=(V?E:E.slice(0,3)).map(j=>{var R,G,te;return{...j,scenarioCount:((te=(G=(R=j.analyses)==null?void 0:R[0])==null?void 0:G.scenarios)==null?void 0:te.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:E.length>0&&l("div",{className:"space-y-1.5",children:[O.map((j,R)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(wr,{entity:j,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:j.scenarioCount})}),R===0&&H&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:H})]},j.sha)),E.length>3&&n("button",{onClick:()=>{v(j=>{const R=new Set(j);return R.has($)?R.delete($):R.add($),R})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Cr,"aria-label":V?"Show fewer entities":`Show ${E.length-3} more entities`,children:V?"Show less":`+${E.length-3} more`})]})},$)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(se,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(pt,{projectSlug:t,onClose:()=>h(!1)})]})}function Je(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function cn(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:h,updated_at:u,...p}=e,m=(i??[]).map(g=>g.branch_id),f=c?c.map(it):void 0,y=d?_t(d):void 0;return Je({...p,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:y,analyses:f,branchIds:m,createdAt:h,updatedAt:u})}function na(e){return Je({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 ra(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:h,...u}=e;return Je({...u,branches:t?t.map(Dt):void 0,files:r?r.map(na):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function Kl(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Je({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:c})}function Ql(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:c,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Je({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:c,user:h})}function Xs(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,h=s?it(s):void 0,u=o?o.map(Kl):void 0,p=i?i.map(Ql):void 0;return Je({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:h,userScenarios:u,comments:p})}function Zl(e){return Je({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?it(e.analysis):void 0,entity:e.entity?cn(e.entity):void 0,branch:e.branch?Dt(e.branch):void 0,createdAt:e.created_at})}function it(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:h,entity:u,commit:p,project:m,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:C,created_at:N,updated_at:k,indirect:w,...A}=e,M=u?cn(u):void 0,I=h?na(h):void 0,D=m?ra(m):void 0,L=p?_t(p):void 0,_=f?f.map(Xs):void 0,S=y?y.map(Zl):void 0,T=S?S.map(F=>F.branch):void 0;return Je({...A,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:M,file:I,commit:L,project:D,scenarios:_,analysisBranches:S,branches:T,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:C,createdAt:N,updatedAt:k,indirect:!!w})}function aa(e){return Je({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?_t(e.commit):void 0,branch:e.branch?Dt(e.branch):void 0})}function Xl(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return Je({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function _t(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:h,analyses:u,entities:p,commit_branches:m,committed_at:f,analyzed_at:y,...g}=e,x=a?Dt(a):void 0,v=i?Dt(i):void 0,b=(s==null?void 0:s.length)>0?Xl(s[s.length-1]):void 0,C=(u??[]).map(it),N=(p??[]).map(cn),k=(m==null?void 0:m.length)>0?m.map(aa):void 0;return h&&(h.username=h.preferredUsername??h.username),Je({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:c,htmlUrl:d,author:h,analyses:C,entities:N,commitBranches:k,committedAt:f,analyzedAt:y})}function Dt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:c,primary:d,...h}=e,u=a?a.map(_t):void 0,p=s?s.flatMap(m=>it(m.analysis)):void 0;return Je({...h,projectId:t,contentChangedAt:r,commits:u,analyses:p,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var Vn;class ec{constructor(){Va(this,Vn,new tc)}transformQuery(t){return Ha(this,Vn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Vn=new WeakMap;class tc extends ul{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const X=()=>null,nc={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()},rc=Object.keys(nc),ac={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},sc=Object.keys(ac),oc={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()},eo=Object.keys(oc),ic={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()},to=Object.keys(ic);to.filter(e=>e!=="files");const lc={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()},no=Object.keys(lc),cc={active:X(),branch_id:X(),entity_sha:X()},dc=Object.keys(cc),uc={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},hc=Object.keys(uc),mc={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},Rn=Object.keys(mc),pc=!!Mt("ENABLE_QUERY_LOGGING"),fc=!!Mt("ENABLE_QUERY_ERROR_LOGGING");Mt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let yn;function ke(){if(!yn){const e=ao();if(e==="sqlite")yn=gc();else if(e==="postgresql")yn=yc();else throw new Error(`Unknown database type: ${e}`)}return yn}function gc(e){if(e||(e=Mt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=Z.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new ll(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const s=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&s.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(s){console.error("CodeYam DB ERROR: Failed to verify database schema:",s)}return new Hs({dialect:new ml({database:a}),plugins:[new hl,new ec],log:ro})}function yc(){const e=bc();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new cl({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Hs({dialect:new pl({pool:t}),log:ro})}let Nr=null;function It(){return Nr||(Nr=xc(ao())),Nr}function ro(e){e.level==="error"?fc&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):pc&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function xc(e){if(e==="sqlite")return fl;if(e==="postgresql")return gl;throw new Error(`Unknown database type: ${e}`)}function ao(){if(Mt("SQLITE_PATH"))return"sqlite";if(Mt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function bc(){const e=Mt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Mt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var dn=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(dn||{});const Xn="Default Scenario";let vc="<main>";function wc(){return vc}function ns(e,...t){we(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function we(...e){const t=wc(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
21
- ${s.stack}`:typeof s=="object"?Cc(s):String(s)}).filter(Boolean).join(`
22
- `),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
23
- `);return}console.log(a.replace(/\n/g,"\r"))}function Cc(e,t=2){function r(a,s=new WeakMap){return a===null||typeof a!="object"?a:s.has(a)?`"[Circular: ${a.constructor.name}]"`:(s.set(a,!0),Array.isArray(a)?`[${a.map(c=>{const d=r(c,s);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=r(c,s):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const s=r(e);if(!t)return s;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:a,serialized:s}),s}}}function Dn(e,t){try{let r=function(o){var i,c;if(je.isFunctionDeclaration(o)&&Vt(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(a),u=Sr(o);s.push({name:d,code:h,sha:wt(t,d,h),entityType:"function",isDefault:u})}else if(je.isClassDeclaration(o)&&Vt(o)){const d=((c=o.name)==null?void 0:c.text)||"default",h=o.getText(a),u=Sr(o),p=h.includes("React.")||h.includes("jsx")||h.includes("tsx");s.push({name:d,code:h,sha:wt(t,d,h),entityType:p?"component":"class",isDefault:u})}else if(je.isInterfaceDeclaration(o)&&Vt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:wt(t,d,h),entityType:"interface",isDefault:!1})}else if(je.isTypeAliasDeclaration(o)&&Vt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:wt(t,d,h),entityType:"type",isDefault:!1})}else if(je.isVariableStatement(o)&&Vt(o)){const d=Sr(o);o.declarationList.declarations.forEach(h=>{var u;if(je.isIdentifier(h.name)){const p=h.name.text,m=o.getText(a),f=((u=h.initializer)==null?void 0:u.getText(a))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:p,code:m,sha:wt(t,p,m),entityType:y?"component":"variable",isDefault:d})}})}else if(je.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:wt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(je.isExportDeclaration(o)&&o.exportClause&&je.isNamedExports(o.exportClause)){const d=o.getText(a);for(const h of o.exportClause.elements){const u=h.name.text;s.push({name:u,code:d,sha:wt(t,u,d),entityType:"unknown",isDefault:!1})}}je.forEachChild(o,r)};const a=je.createSourceFile(t,e,je.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Vt(e){if(!je.canHaveModifiers(e))return!1;const t=je.getModifiers(e);return t?t.some(r=>r.kind===je.SyntaxKind.ExportKeyword):!1}function Sr(e){if(!je.canHaveModifiers(e))return!1;const t=je.getModifiers(e);return t?t.some(r=>r.kind===je.SyntaxKind.DefaultKeyword):!1}function wt(e,t,r){const a=qn.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function Nc(e){var h;const{webapp:t,port:r,environmentVariables:a,packageManager:s}=e,o=t==null?void 0:t.startCommand;if(!o)return`${s} ${s==="npm"?"run ":""}dev`;const i=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],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(o.env)for(const[u,p]of Object.entries(o.env)){const f=String(p).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function Sc(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=Z.normalize(e),a=[...t].sort((s,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=s.path)==null?void 0:c.length)??0)});for(const s of a){const o=Z.normalize(s.path??".");if(o==="."||r.startsWith(o+Z.sep)||r===o)return s}return t[0]}function Ec(e){const{filePath:t,webapps:r,environmentVariables:a,port:s,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=Sc(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=Nc({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${s}/static/codeyam-sample`}}function er(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function Ac(e){const{jsonObjectFrom:t}=It();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function kc({ids:e,analysisId:t}){const r=ke();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw we("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw we("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function Pc(...e){try{const t=qn.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function Er(e,t){return t.map(r=>_c(e,r))}function _c(e,t){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(t)}function Mc(e,t,r){return t.map(a=>Tc(e,a,r))}function Tc(e,t,r){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(`_cy_${r}:${t}`)}function jc(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const Ic=50;function $c(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,a)=>e.slice(a*t,a*t+t))}function rs({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const h=ke(),{jsonObjectFrom:u,jsonArrayFrom:p}=It();let m=d?h.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"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return a&&(m=m.where("entity_name","=",a)),s&&(m=m.where("entity_sha","in",s)),i&&(m=m.where("branch_commit_sha","=",i)),c&&(m=m.limit(c)),d?h.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("scenarios").select(Er("scenarios",Rn)).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")]):h.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(Er("entities",no)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),p(f.selectFrom("scenarios").select(Er("scenarios",Rn)).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 ft(e){const{ids:t,fileIds:r,entityShas:a,commitIds:s}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:s,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let c=[];if(i){const[d,{arr:h,key:u}]=i,p=$c(h,Ic),m=[];for(let f=0;f<p.length;f++){const y=p[f],x=await rs({...e,[u]:y}).execute();x&&m.push(...x)}c=m}else{const h=await rs(e).execute();if(!h||h.length===0)return we("CodeYam: No analyses found",null,e),null;c=h}return c.length===0?null:c.map(it)}catch(o){return we("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Rc(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=It();let s=e.selectFrom("analysis_branches").select(sc).select(o=>a(o.selectFrom("branches").select(eo).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function lt({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:p,includeBranches:m}){const f=ke(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):a&&(g=g.where("file_id","=",a)),o&&(g=g.where("entity_name","=",o)),s?g=g.where("commit_id","=",s):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=It();g=g.select(N=>{const k=[];return k.push(x(N.selectFrom("entities").select(no).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&k.push(x(N.selectFrom("files").select(hc).whereRef("files.id","=","analyses.file_id")).as("file")),h&&k.push(x(N.selectFrom("projects").select(rc).whereRef("projects.id","=","analyses.project_id")).as("project")),p&&k.push(v(N.selectFrom("scenarios").select(Rn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),m&&k.push(Rc(N,w=>w.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&k.push(x(N.selectFrom("commits").select(to).select(w=>Ac(w).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),k});const b=await g.executeTakeFirst(),C=Date.now()-y;if(!b)return we("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:p,includeBranches:m}),null;if(C>100&&u){const N=b.commit,k=N!=null&&N.files?JSON.stringify(N.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${C}ms (files: ${Math.round(k/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return it(b)}catch(g){return we("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:p,includeBranches:m}),null}}async function so({projectId:e,ids:t,names:r,includeInactive:a}){const s=ke();try{let o=s.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return a||(o=o.where("active_at","is not",null)),(await o.execute()).map(Dt)}catch(o){return we("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function Dc({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ke();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,h=>h.select(Mc("branches",eo,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const c=await i.execute();return!c||c.length===0?null:c.map(h=>jc(h,"branch")).map(aa)}catch(i){return we("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function Lc(e){if(e.length===0)return new Map;const t=ke();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(o=>{o.branch_id&&a.add(o.branch_id),o.merged_branch_id&&a.add(o.merged_branch_id)}),a.size===0)return new Map;const s=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(s.map(o=>[o.id,o]))}catch(r){return we("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Fc(e){if(e.length===0)return new Map;const t=ke(),{jsonObjectFrom:r,jsonArrayFrom:a}=It();try{const s=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(Rn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(s){return we("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function Oc(e){if(e.length===0)return new Map;const t=ke();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(s=>{const o=a.get(s.commit_id)||[];o.push(s),a.set(s.commit_id,o)}),a}catch(r){return we("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Ln({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=ke(),{jsonObjectFrom:d}=It(),h=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)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(s&&s.length>0){const b=Ke.join(s.map(C=>Ke`${C}`),Ke`, `);u=u.where(Ke`
24
- EXISTS (
25
- SELECT 1
26
- FROM json_each(${Ke.ref("commits.files")}) AS f
27
- WHERE json_extract(f.value, '$.fileName') IN (${b})
28
- )
29
- `)}t&&(u=u.where("branch_id","=",t));const p=await u.orderBy("committed_at","desc").limit(o).execute(),m=Date.now()-h;if(!p||p.length===0)return[];if(m>100){const b=p.reduce((C,N)=>C+(N.files?JSON.stringify(N.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${m}ms (${p.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return p.map(C=>({...C,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(_t);const f=p.map(b=>b.id),[y,g,x]=await Promise.all([Lc(f),Fc(f),Oc(f)]);return p.map(b=>{const C=b.branch_id?y.get(b.branch_id):void 0,N=b.merged_branch_id?y.get(b.merged_branch_id):void 0,k=g.get(b.id)||[],w=x.get(b.id)||[];return{...b,branch:C,mergedBranch:N,analyses:k,entities:w}}).map(_t)}catch(u){return we("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function at({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o,excludeMetadata:i}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let h=0;h<o.length;h+=50){const u=o.slice(h,h+50),p=await at({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:u,excludeMetadata:i});p&&d.push(...p)}return d}const c=ke();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(!!t,p=>p.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,p=>p.where("entities.project_id","=",e)).$if(!!o,p=>p.where("entities.sha","in",o)).$if(!!a,p=>p.where("entities.file_path","in",a)).$if(!!s,p=>p.where("entities.name","in",s)).$if(!!r,p=>p.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):u.map(cn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function zc(e,t){const{jsonArrayFrom:r}=It();let a=e.selectFrom("entity_branches").select(dc);return t&&(a=t(a)),r(a)}async function oo({projectId:e,sha:t}){const r=ke();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>zc(s,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?cn(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&we("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return we("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Ar=1e3;async function io({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const h=t.slice(d,d+50),u=await io({projectId:e,filePaths:h,fileIds:r,fileNames:a});u&&c.push(...u)}return c}const s=ke(),o=[];let i=0;try{for(;;){let c=s.selectFrom("files").selectAll().where("project_id","=",e).limit(Ar).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(a){if(a.length===0)return[];c=c.where("name","in",a)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<Ar))break;i+=Ar}return o==null?void 0:o.map(na)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function Yc({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ke().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=ra(c);return a&&(d.files=await io({projectId:d.id})),r&&(d.branches=await so({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Fn(e,t){const r={...e};for(const a in t){const s=t[a],o=e[a];s!=null&&typeof s=="object"&&!Array.isArray(s)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[a]=Fn(o,s):s!==void 0&&(r[a]=s)}return r}async function mt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ke().transaction().execute(async i=>{var u,p;const c=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,m=>m.where("id","=",e)).$if(!!t,m=>m.where("sha","=",t)).executeTakeFirst();if(!c)return we(`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: ${t}`),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:",s)),r=Fn(r??{},{currentRun:a});else if(!r&&!o)return d;const h=r?Fn(d,r):d;if(s&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((p=h.historicalRuns)==null?void 0:p.length)||0}`);const m={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(m,null,2)),h.historicalRuns=[...h.historicalRuns||[],m],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(h);try{return await i.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",c.id).returning(["id"]).executeTakeFirst()?h:(we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(m){return we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,m),d}})}catch(i){return we(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function lo(e,t,r="analysis"){try{return await ke().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=it(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(we(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Ft(e,t,r="capture"){try{return await ke().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=it(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(we(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function On({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ke().transaction().execute(async s=>{const o=await s.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return we(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const c=r?Fn(i,r):i;a&&await a(c,ra(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return we(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}const Bc=()=>crypto.randomUUID();function Uc(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Bc(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function Wc(e){if(e.length===0)return[];const t=ke(),r=e.map(Uc);try{return(await t.insertInto("scenarios").values(r).onConflict(er(r[0],"id",["created_at"])).returningAll().execute()).map(Xs)}catch(a){return we("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}const Hc=()=>crypto.randomUUID();function Vc(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??Hc(),commit_id:r,branch_id:a}}async function as(e){if(e.length===0)return[];const t=ke(),r=e.map(Vc);try{return(await t.insertInto("commit_branches").values(r).onConflict(er(r[0],"id",["created_at"])).returningAll().execute()).map(aa)}catch(a){return we("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function Jc(e,t){const r=ke(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(er(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return we("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}const Gc=()=>crypto.randomUUID();function qc(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:h,author:u,metadata:p,files:m,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Gc(),project_id:a??String(t),metadata:p?JSON.stringify(p):void 0,files:m?JSON.stringify(m):void 0,branch_id:s,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:h}}async function Kc({projectId:e,commits:t}){const r=ke();try{const a=t.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 Jc(i,a[i]);const s=t.map(i=>qc(i,e));return(await r.insertInto("commits").values(s).onConflict(er(s[0],"id",["created_at"])).returningAll().execute()).map(_t)}catch(a){return we("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const zn=Z.join(xl.homedir(),".codeyam","secrets.json"),Yn=Z.join(process.cwd(),".codeyam","secrets.json");async function yt(){let e={};try{if(K.existsSync(Yn)){const o=await Re.readFile(Yn,"utf8");e=JSON.parse(o)}}catch{console.warn($n.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(zn)){const o=await Re.readFile(zn,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn($n.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(t.ANTHROPIC_API_KEY=a);const s=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return s&&(t.GROQ_API_KEY=s),t}async function Qc(e,t=!0){const r=t?zn:Yn,a=Z.dirname(r);await Re.mkdir(a,{recursive:!0}),await Re.writeFile(r,JSON.stringify(e,null,2)),await Re.chmod(r,384)}function Zc(e=!0){return e?zn:Yn}async function ss(){const e=await yt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Xc(e){console.log(),console.log($n.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await bl({type:"password",name:"key",message:"OpenAI API Key",validate:s=>s&&!s.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function ed(e=!0){const t=await ss();if(t.isValid)return t.secrets;const r=await Xc(t.missing),s={...await yt(),...r};await Qc(s,e);const o=Zc(e);return console.log($n.green(`✓ Configuration saved to ${o}`)),(await ss()).secrets}function co(e=process.cwd()){let t=Z.resolve(e);const r=Z.parse(t).root;for(;t!==r;){const s=Z.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=Z.dirname(t)}const a=Z.join(r,".codeyam","config.json");return K.existsSync(a)?r:null}let uo=co();function ge(){return uo}function td(e){uo=e}function ho(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const nd={"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>`};ho(nd);const rd={"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>`};ho(rd);function Kt(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=Kt(s[i],c,r):o[i]=c}return o}const a={...e};for(const s in t)if(t[s]===null)a[s]=null;else if(Array.isArray(t[s])){const o=Array.isArray(e[s])?e[s]:[];a[s]=[];for(let i=0;i<t[s].length;i++){const c=t[s][i];typeof c=="object"&&c!==null?a[s][i]=Kt(o[i],c,r):a[s][i]=c}}else typeof t[s]=="object"&&t[s]!==null?a[s]=Kt(a[s]??{},t[s],r):a[s]=t[s];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function ad({projectId:e,commit:t,branch:r}){var c,d,h,u,p,m,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await Dc({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(c=o.sort((g,x)=>{var v,b,C,N;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((N=(C=x.branch.metadata)==null?void 0:C.permanent)==null?void 0:N.order)??999)})[0])==null?void 0:c.branch,a&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((p=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:p.order)<=((f=(m=a.metadata)==null?void 0:m.permanent)==null?void 0:f.order)?a=r:s.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==a.id||!g.active&&g.branch.id===a.id);y.length>0&&await as(y.map(g=>({...g,active:g.branchId===a.id})))}(o==null?void 0:o.find(y=>y.branchId===s.branchId))||await as([s])}function xt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=ge();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ie.join(e,".codeyam","db.sqlite3")}async function Le(){const e=await ed();process.env.SQLITE_PATH=xt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ie(e){await Le();const t=await Yc({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await so({projectId:t.id,names:["_local"]}),a=r==null?void 0:r[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:t,branch:a}}async function sd(e,t,r){await Le();const a=ge(),s=Pc(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(a)try{if(h=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const p=u.split(`
30
- `);h=`@@ -0,0 +1,${p.length} @@
31
- ${p.map(m=>`+${m}`).join(`
32
- `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:s,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${s}`,htmlUrl:`local://codeyam/${e.slug}/${s}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await Kc({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await ad({projectId:e.id,commit:c[0],branch:t}),c[0]}async function un(){await Le();const e=await at({excludeMetadata:!0});if(!e||e.length===0)return[];const t=e.filter(d=>{var h;return!((h=d.metadata)!=null&&h.isSuperseded)}),r=t.map(d=>d.sha),a=t.map(d=>{var h;return(h=d.metadata)==null?void 0:h.previousVersionWithAnalyses}).filter(d=>!!d),s=[...new Set([...r,...a])],o=await ft({entityShas:s,excludeMetadata:!0}),i=new Map;if(o)for(const d of o)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return t.map(d=>{var p;const h=i.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=(p=d.metadata)==null?void 0:p.previousVersionWithAnalyses;if(u){const m=i.get(u)||[];return{...d,analyses:m}}return{...d,analyses:[]}})}async function tr(e,t){await Le();const r=await ft({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await oo({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function sa(e){if(await Le(),e.name&&e.projectId){const r=await ft({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0];const s=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0]}}const t=await ft({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function mo(e){await Le();const t=await ft({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Lt(e){await Le();const t=await $e();if(!t)return null;const{project:r}=await Ie(t);return await oo({projectId:r.id,sha:e})}async function po(e){var a,s,o,i,c,d,h,u;await Le();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const p=e.metadata.importedExports;for(const m of p){if(!m.filePath||!m.name)continue;const f=m.resolvedFilePath??m.filePath,y=m.resolvedName??m.name;let g=await at({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&m.resolvedIsDefault&&(g=await at({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await ft({entityShas:[x.sha],limit:1});let b,C,N;if(v&&v.length>0&&v[0].scenarios){const k=v[0],w=k.scenarios||[],A=w.length,M=w.find(D=>{var L,_;return(_=(L=D.metadata)==null?void 0:L.screenshotPaths)==null?void 0:_[0]});M&&(b=(o=(s=M.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],C=M.name),N={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||k.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:A,timestamp:k.createdAt?new Date(k.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else N={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:C,analysisStatus:N})}}}if((c=e.metadata)!=null&&c.importedBy){const p=[];for(const m in e.metadata.importedBy)for(const f in e.metadata.importedBy[m]){const y=e.metadata.importedBy[m][f];y.shas&&p.push(...y.shas)}if(p.length>0){const m=await at({projectId:e.projectId,shas:p});if(m)for(const f of m){const y=await ft({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],C=b.scenarios||[],N=C.length,k=C.find(A=>{var M,I;return(I=(M=A.metadata)==null?void 0:M.screenshotPaths)==null?void 0:I[0]});k&&(g=(h=(d=k.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],x=k.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function $e(){try{const e=ge();if(!e)return null;const t=ie.join(e,".codeyam","config.json");return JSON.parse(await fe.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Ot(){await Le();try{const e=await $e();if(!e)return null;const{project:t,branch:r}=await Ie(e),a=await Ln({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function nr(){try{const e=ge();if(!e)return null;const t=ie.join(e,".codeyam","config.json");return JSON.parse(await fe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function fo(e){try{const t=ge();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ie.join(t,e.filePath);return await fe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function go(e){try{const t=ge();if(!t||!e.filePath)return!1;const r=ie.join(t,e.filePath),s=(await fe.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return s>i+1e3}catch{return!1}}async function yo(e){if(await Le(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await at({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await ft({entityShas:r}),s=new Map;if(a)for(const i of a)s.has(i.entitySha)||s.set(i.entitySha,[]),s.get(i.entitySha).push(i);for(const[i,c]of s.entries())c.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,c)=>{var u,p;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((p=c.analyses[0])==null?void 0:p.createdAt)||c.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function xo(e){try{const t=ge();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ie.join(t,".codeyam","config.json"),a=await fe.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await fe.writeFile(r,i,"utf8"),s.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 On({projectSlug:s.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const od=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:un,getAnalysesForEntity:tr,getAnalysisForExactEntitySha:mo,getCurrentCommit:Ot,getEntityBySha:Lt,getEntityCodeFromFilesystem:fo,getEntityHistory:yo,getLatestAnalysisForEntity:sa,getProjectConfig:nr,getProjectSlug:$e,getRelatedEntities:po,hasFileBeenModifiedSinceEntity:go,requireBranchAndProject:Ie,updateProjectConfig:xo},Symbol.toStringTag,{value:"Module"})),bo="secrets.json";function vo(e){return ie.join(e,".codeyam",bo)}function wo(){return ie.join(Fr.homedir(),".codeyam",bo)}async function rr(e){let t={};try{const r=wo(),a=await fe.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=vo(e),a=await fe.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function id(e,t,r=!0){const a=r?wo():vo(e),s=ie.dirname(a);await fe.mkdir(s,{recursive:!0}),await fe.writeFile(a,JSON.stringify(t,null,2)+`
33
- `,"utf-8")}async function ld(e){const t=await rr(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const cd=3;let Jt=0;async function xn(e){if(!e||e.length===0)return[];if(Jt>=cd)return console.warn(`[Loader] Circuit breaker open (${Jt} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let a=!1;const s=setTimeout(()=>{a||(a=!0,Jt++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);at({shas:e,excludeMetadata:!0}).then(o=>{a||(a=!0,clearTimeout(s),Jt=0,r(o||[]))}).catch(()=>{a||(a=!0,clearTimeout(s),Jt++,r([]))})})}function dd({sourcePath:e,destinationPath:t,excludes:r,silent:a}){if(process.platform!=="darwin")return!1;if(rt(t))try{if(dl(t).length>0)return!1;vr(t,{recursive:!0})}catch{return!1}try{Me(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const s of r)if(s.includes("*"))try{Me(`rm -rf "${Qa(t,s)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=Qa(t,s);rt(o)&&vr(o,{recursive:!0,force:!0})}return a||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(rt(t))try{vr(t,{recursive:!0})}catch{}return!1}}async function ud({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){const i=Date.now();if(!a&&o.length===0&&dd({sourcePath:e,destinationPath:t,excludes:r,silent:s})){if(!s){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((c,d)=>{const h=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,p=["-a"];a||p.push("--delete","--force"),p.push(...o);for(const f of r)p.push(`--exclude=${f}`);p.push(h,u);const m=Kn("rsync",p);m.on("exit",f=>{if(f===0){if(!s){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}c()}else d(new Error(`rsync failed with exit code ${f}`))}),m.on("error",f=>{s||console.log("Error occurred:",f),d(f)})})}const hd=Zr(Qr);async function md(e){return new Promise(t=>setTimeout(t,e))}function pd(e){try{return process.kill(e,0),!0}catch{return!1}}async function Co(e){try{const{stdout:t}=await hd(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
- `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await Co(s);a.push(...o)}return a}catch{return[]}}function os(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function fd(e,t,r){const a=await Co(e);for(const s of a.reverse())await os(s,t,r);await os(e,t,r)}async function rn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function s(o,i){await fd(e,o,t);for(let c=0;c<i;c++)if(await md(1e3),a+=1e3,!await pd(e))return t(`Process tree ${e} successfully killed with ${o} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await s("SIGINT",5)||await s("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await s("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function gd(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:$l(),createdAt:t}}Cl.config({quiet:!0});var No=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(No||{});class yd extends Nl{constructor(){super(...arguments),this.processes=new Map}register(t){const r=El(),{process:a,type:s,name:o,metadata:i,parentId:c}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:a}),c){const p=this.processes.get(c);p&&(p.info.children=p.info.children||[],p.info.children.push(r))}const h=(p,m)=>{this.handleProcessExit(r,p,m)},u=p=>{this.handleProcessError(r,p)};return a.on("exit",h),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",h),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(c=>this.shutdown(c,r))),o.pid)try{await rn(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,100)),s.state==="running"&&(s.state="killed",s.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(s=>this.shutdown(s.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[s,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const c=o.process.__cleanup;c&&c(),this.processes.delete(s)}}}handleProcessExit(t,r,a){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.exitCode=r,o.signal=a,r===0?o.state="completed":a?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:s}=a;s.endedAt=Date.now(),s.state="failed",s.metadata={...s.metadata,error:r.message},this.emit("processExited",s)}}let kr=null;function xd(){return kr||(kr=new yd),kr}const bd={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function vd({command:e,args:t,workingDir:r,outputOptions:a=bd,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},c=Kn(e,t,{cwd:r,env:i});return xd().register({process:c,type:No.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const p=f=>{const y=ie.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},m=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
35
- `).map(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
36
- `)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(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=m(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 wd(e){const t=[];return Object.keys(e).forEach(r=>{const a=e[r];a!==void 0&&(typeof a=="boolean"?a&&t.push(`--${r}`):a!==null&&t.push(`--${r}`,String(a)))}),t}function Cd({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
39
- `);K.writeFileSync(`${e}/.env`,s);const o=wd(r);return vd({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const Nd="/tmp/codeyam/local-dev";function So(e){return Z.join(Nd,e)}function Eo(e){return Z.join(So(e),"codeyam")}function ct(e){return Z.join(So(e),"project")}function ar(e){return Z.join(Eo(e),"log.txt")}const Sd=[".sync-metadata.json","__codeyamMocks__"];async function Ed(e,t={}){const{port:r,silent:a=!0}=t,s=ct(e);if(r)try{Me(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${s}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function Ad(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=ct(e),i=[],c=[];if(!K.existsSync(o))return{removed:i,errors:c};r&&await Ed(e,{port:a,silent:s});for(const d of Sd){const h=Z.join(o,d);if(K.existsSync(h))try{(await Re.stat(h)).isDirectory()?await Re.rm(h,{recursive:!0,force:!0}):await Re.unlink(h),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const kd=Z.dirname(Qn(import.meta.url));function Pd(e){let t=e;for(;t!==Z.dirname(t);){const r=Z.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=Z.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function sr(){const e=Pd(kd);return Z.join(e,"analyzer-template")}function zt(e){return Eo(e)}function _d(){const e=sr();return K.existsSync(Z.join(e,".finalized"))}async function is(e){const t=sr(),r=zt(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Re.mkdir(Z.dirname(r),{recursive:!0}),await ud({sourcePath:t,destinationPath:r,silent:!0})}function Yt(e,t,r,a){const s=zt(e);if(!K.existsSync(s))throw new Error(`Analyzer not found at ${s}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Cd({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Md(e){const t=sr(),r=zt(e),a=Z.join(t,".build-info.json"),s=Z.join(r,".build-info.json");if(!K.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(a,"utf8")),i=JSON.parse(K.readFileSync(s,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function hn(e,t){const r=zt(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await is(e);return}const a=Md(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await is(e))}async function oa(e){await Ad(e,{killProcesses:!1})}const Td=Z.dirname(Qn(import.meta.url));function ia(){let e=Td;for(;e!==Z.dirname(e);){const t=Z.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=Z.dirname(e)}return null}function Xt(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function jd(){const e=ia();if(e){const t=[Z.join(e,"src/webserver/build-info.json"),Z.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const a=Xt(r);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}function Id(){const e=ia();if(e){const t=Z.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const la=jd(),$d=Id();function Ao(e){const t=ia();let r=null;if(t){const d=[Z.join(t,"src/webserver/build-info.json"),Z.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const h of d)if(r=Xt(h),r)break}const a=sr(),s=Z.join(a,".build-info.json"),o=Xt(s);let i=null;if(e){const d=zt(e),h=Z.join(d,".build-info.json");i=Xt(h)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:la,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function or(e){const t=zt(e),r=Z.join(t,".build-info.json"),a=Xt(r);return(a==null?void 0:a.version)??null}function ko(){const e=ge();return e?Z.join(e,".codeyam","server.json"):null}function Po(){const e=ko();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Rd(){const e=ko();if(e)try{K.unlinkSync(e)}catch{}}const Dd="/assets/globals-CCgBKWy4.css";function ls({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=P(!1);return s?null:n("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:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(se,{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:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Ld(){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Fd({serverVersion:e}){const[t,r]=P("stale"),[a,s]=P(null),o=async()=>{r("restarting"),s(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),h):(s("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){s(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(he,{children:[n("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&&n("p",{className:"text-xs text-red-600 mt-1",children:a})]}),t==="restarting"&&l(he,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(he,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function Od({currentVersion:e,latestVersion:t}){const[r,a]=P(!1),[s,o]=P(!1);if(r)return null;const i="npm install -g @codeyam/codeyam-cli@latest",c=async()=>{try{await navigator.clipboard.writeText(i),o(!0),setTimeout(()=>o(!1),2e3)}catch{}};return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 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:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),l("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),l("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:i}),n("button",{type:"button",onClick:()=>void c(),className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors cursor-pointer",children:s?"Copied!":"Copy"})]})]}),n("button",{type:"button",onClick:()=>a(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Gt=null,bn=0;const zd=3600*1e3;function Yd(e,t){const r=e.split(".").map(Number),a=t.split(".").map(Number);for(let s=0;s<Math.max(r.length,a.length);s++){const o=r[s]??0,i=a[s]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function Bd(){const e=$d;if(Gt&&Date.now()-bn<zd)return Gt;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),a=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!a.ok){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Gt=c,bn=Date.now(),c}const o=(await a.json()).version;if(!o){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Gt=c,bn=Date.now(),c}const i={updateAvailable:Yd(o,e),latestVersion:o,currentVersion:e};return Gt=i,bn=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Bn(e){return Z.join(e,".codeyam","queue.json")}function Qt(e){const t=Bn(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Ud(e,t){const r=Bn(e),a=Z.dirname(r);K.existsSync(a)||K.mkdirSync(a,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function Wd(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Hd(e,t,r);else if(e.type==="baseline")await Vd(e,t,r);else if(e.type==="recapture")await Jd(e,t,r);else if(e.type==="capture-only")await Gd(e,t,r);else if(e.type==="debug-setup")await qd(e,t,r);else if(e.type==="interactive-start")await Kd(e,t,r);else if(e.type==="interactive-stop")await Qd(e,t,r);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 Hd(e,t,r){var g,x,v,b;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await Ie(a);await oa(a),await hn(a,{update:C=>console.log(`[Queue] ${C}`)});const d=or(a),h={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const p=e.onlyDataStructure,m={packageManager:((v=c.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:ct(a),port:0,noServer:!0,framework:u.framework,...p?{}:{orchestrateCapture:"local-sequential"}},f=Yt(a,h,m),y=C=>{try{return process.kill(C,0),!0}catch{return!1}};await mt({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const C=new Promise((N,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,C]),await mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await mt({commitSha:s,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(N=>setTimeout(N,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await rn(f.process.pid,()=>{})}catch{}}}catch(C){if(console.error(`[Queue] Analysis job ${e.id} failed:`,C),f.process.pid&&y(f.process.pid))try{await rn(f.process.pid,()=>{})}catch{}try{await mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:C instanceof Error?C.message:String(C)}}),r==null||r.notifyChange("commit")}catch(N){console.error("[Queue] Failed to update commit metadata after job failure:",N)}throw C}}async function Vd(e,t,r){var m,f,y;const{projectSlug:a,commitSha:s}=e;if(!s)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:o}=await Ie(a);await oa(a),await hn(a,{update:g=>console.log(`[Queue] ${g}`)});const i=or(a),c={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(m=o.metadata)==null?void 0:m.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:ct(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=Yt(a,c,h),p=g=>{try{return process.kill(g,0),!0}catch{return!1}};await mt({commitSha:s,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{p(u.process.pid)&&await rn(u.process.pid,()=>{})}catch{}}}async function Jd(e,t,r){var f,y,g,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const c=await lt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-CXfuiwt3.js"),b=v(),C=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let N={};C!=null&&C.metadata&&(typeof C.metadata=="string"?N=JSON.parse(C.metadata):N=C.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",c.entitySha).execute()}await Ft(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(a);await hn(a,{update:v=>console.log(`[Queue] ${v}`)});const h=or(a),u={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ct(a),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??dn.Next,orchestrateCapture:"local-sequential"},m=Yt(a,u,p);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function Gd(e,t,r){var f,y,g,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const c=await lt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-CXfuiwt3.js"),b=v(),C=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let N={};C!=null&&C.metadata&&(typeof C.metadata=="string"?N=JSON.parse(C.metadata):N=C.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",c.entitySha).execute()}await Ft(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(a);await hn(a,{update:v=>console.log(`[Queue] ${v}`)});const h=or(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ct(a),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??dn.Next,orchestrateCapture:"local-sequential"},m=Yt(a,u,p);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function qd(e,t,r){var m,f,y,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Debug setup job missing analysisId");const i=await lt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a);await oa(a),await hn(a,{update:x=>console.log(`[Queue] ${x}`)});const d={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((m=c.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:ct(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)||dn.Next},p=await Yt(a,d,h).promise;if(p!==0)throw new Error(`Prep process exited with code ${p}`)}async function Kd(e,t,r){var p,m,f,y;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await lt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a),d={...await yt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ct(a),port:void 0,noServer:!1,framework:((y=(f=(m=c.metadata)==null?void 0:m.webapps)==null?void 0:f[0])==null?void 0:y.framework)||dn.Next};await Ft(s,g=>{g.readyToBeCaptured=!0});const u=Yt(a,d,h);await lo(s,g=>{g.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${s}, PID: ${u.process.pid}`)}async function Qd(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await lt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${s} not found`);const i=(d=o.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${s}`);return}const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await rn(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(h){throw console.error(`[Queue] Failed to kill process ${c}:`,h),h}finally{await lo(s,h=>{h.interactiveMode=null})}}class Zd{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=Qt(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(t){const r=t.commitSha||Vs(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,c=>{c?i(c):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(s=>s.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const s=this.completionCallbacks.get(t);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const s=r==="up"?a-1:a+1;if(s<0||s>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[s],this.state.jobs[s]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${s})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Wd(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Ud(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Xd{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=Bn(this.projectRoot);if(!K.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Bn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.watch(r,(a,s)=>{s==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=K.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class eu{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=Qt(r)}start(){this.cachedState=Qt(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 Xd(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const s=new Promise((i,c)=>{r=i,a=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:o,completion:s}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Qt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Qt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function tu(e){const t=Z.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function nu(e){try{return process.kill(e,0),!0}catch{return!1}}async function ru(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}async function au(e){const t=tu(e);return!t||!nu(t.pid)||!await ru(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class su extends Sl{constructor(){super();gn(this,"watcher",null);gn(this,"dbPath",null);gn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=xt();const{default:r}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",s=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${s}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",s=>{console.error("Database watcher error:",s),this.emit("error",s)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const a=Date.now(),s=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${s} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Or=new su;let Et=null,Zt=null;async function ou(){if(!Et){if(Zt){await Zt;return}Zt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||co()||process.cwd();td(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await au(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new eu(t,e,()=>{Or.notifyChange("unknown")});await r.start(),Et=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Zd(e,Or);await r.start(),Et=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Zt}}async function dt(){return Et||await ou(),Et}function iu(){return Et||(Zt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const lu=()=>[{rel:"stylesheet",href:Dd},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],cu={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1};async function du({request:e,context:t}){var r,a,s,o,i,c,d,h,u,p;try{const m=e.signal,f=()=>{if(m.aborted)throw new Response(null,{status:499})};f();const y=ge()||process.cwd(),[g,x,v]=await Promise.all([$e(),rr(y),Bd().catch(()=>null)]);if(!g)throw new Error("Project slug not found");const{project:b,branch:C}=await Ie(g);f();const N=await Ln({projectId:b.id,branchId:C.id,limit:20,skipRelations:!0});f();const k=N.length>0?N[0]:null,w=t.analysisQueue||iu(),A=w==null?void 0:w.getState();f();const M=await Promise.all(((A==null?void 0:A.jobs)||[]).map(async j=>{var G;const R=await xn(j.entityShas||[]);return R.length===0&&((G=j.entityShas)!=null&&G.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",j.id),{...j,entities:R}}));let I=null;if(A!=null&&A.currentlyExecuting){const j=A.currentlyExecuting,R=await xn(j.entityShas||[]);R.length===0&&((r=j.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",j.id),I={...j,entities:R}}const D=I?M.filter(j=>j.id!==I.id):M;let L=((s=(a=k==null?void 0:k.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(L.length===0){const j=((o=k==null?void 0:k.metadata)==null?void 0:o.historicalRuns)||[];if(j.length>0){const G=[...j].sort((te,ce)=>{const pe=te.archivedAt||te.createdAt||"";return(ce.archivedAt||ce.createdAt||"").localeCompare(pe)})[0];if(G){const te=G.analysisCompletedAt||G.createdAt;if(te){const ce=new Date(te).getTime(),me=Date.now()-1440*60*1e3;ce>me&&(L=G.currentEntityShas||[])}}}}const _=await xn(L),S=[];x.ANTHROPIC_API_KEY&&S.push("ANTHROPIC_API_KEY"),x.GROQ_API_KEY&&S.push("GROQ_API_KEY"),x.OPENAI_API_KEY&&S.push("OPENAI_API_KEY"),x.OPENROUTER_API_KEY&&S.push("OPENROUTER_API_KEY"),f();const T=[];for(const j of N){const R=((i=j.metadata)==null?void 0:i.historicalRuns)||[];for(const G of R)T.push(G)}T.sort((j,R)=>{const G=j.archivedAt||j.analysisCompletedAt||j.createdAt||"";return(R.archivedAt||R.analysisCompletedAt||R.createdAt||"").localeCompare(G)});const F=new Set(((c=I==null?void 0:I.entities)==null?void 0:c.map(j=>j.sha))||[]),J=T.filter(j=>!(j.currentEntityShas||[]).some(G=>F.has(G))).slice(0,3),U=new Set;for(const j of J)for(const R of j.currentEntityShas||[])U.add(R);const Y=await xn(Array.from(U)),z=new Map;for(const j of Y)z.set(j.sha,j);const $=J.map(j=>({...j,entities:(j.currentEntityShas||[]).map(R=>z.get(R)).filter(R=>R!=null)})),E=Po(),W=(E==null?void 0:E.cliVersion)??"unknown",H=W!=="unknown"&&W!==la,V=((h=(d=b.metadata)==null?void 0:d.labs)==null?void 0:h.simulations)??!1,ae=V?_d():!1,O={currentRun:(u=k==null?void 0:k.metadata)==null?void 0:u.currentRun,projectSlug:g,currentEntities:_,availableAPIKeys:S,queuedJobCount:D.length,queueJobs:D,currentlyExecuting:I,historicalRuns:$,isServerOutOfDate:H,serverVersion:W,npmUpdate:v!=null&&v.updateAvailable&&v.latestVersion?{latestVersion:v.latestVersion,currentVersion:v.currentVersion}:null,labs:((p=b.metadata)==null?void 0:p.labs)??null,simulationsEnabled:V,isSimulationsReady:ae,isAdmin:!!process.env.CODEYAM_ADMIN};return B(O)}catch(m){return m instanceof Response&&m.status===499||console.error("Failed to load root data:",m),B(cu)}}function uu(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:h,npmUpdate:u,labs:p,simulationsEnabled:m,isSimulationsReady:f,isAdmin:y}=Be(),{toasts:g,closeToast:x}=ta(),v=ot(),b=Ne(v),C=Jn();ee(()=>{b.current=v},[v]);const N=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/"),k=C.pathname.includes("/fullscreen");return ee(()=>{const w=new EventSource("/api/events");let A=null,M=0;const I=2e3;return w.addEventListener("message",D=>{const L=JSON.parse(D.data);if(L.type==="queue")b.current.revalidate(),M=Date.now();else if(L.type==="db-change"||L.type==="unknown"){const _=Date.now(),S=_-M;S<I?(A&&clearTimeout(A),A=setTimeout(()=>{b.current.revalidate(),M=Date.now(),A=null},I-S)):(b.current.revalidate(),M=_)}}),w.addEventListener("error",D=>{console.error("SSE connection error:",D)}),()=>{A&&clearTimeout(A),w.close()}},[]),l(he,{children:[l("div",{className:`min-h-screen ${N?"":"grid"} bg-cygray-10`,style:N?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!N&&n(Hl,{labs:p,isAdmin:y}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(Fd,{serverVersion:h}),u&&n(Od,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),m&&a.length===0&&n(ls,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),m&&!f&&n(ls,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(_i,{})}),n(Ld,{})]})]}),n(Gl,{toasts:g,onClose:x}),!k&&m&&n(ql,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const hu=De(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Ei,{}),n(Ai,{})]}),l("body",{children:[n(Vl,{children:n(Ul,{children:n(uu,{})})}),n(ki,{}),n(Pi,{})]})]})}),mu=Object.freeze(Object.defineProperty({__proto__:null,default:hu,links:lu,loader:du},Symbol.toStringTag,{value:"Module"}));function cs(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function mn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=Ae(),[c,d]=P(null),[h,u]=P(!1),[p,m]=P(!1),[f,y]=P(!1),g=Ne(!1),x=Ne(null),v=Ne(null),[b,C]=P(0),[N,k]=P(0),w=Ne(null),A=Ne(!1),{interactiveUrl:M,resetLogs:I}=gt(a,s),D=Ne(t),L=Ne(o);ee(()=>{L.current!==o&&(L.current=o,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),m(!0),y(!1),C(0),k(S=>S+1),A.current=!1,w.current&&(clearTimeout(w.current),w.current=null)))},[o,c]),ee(()=>{if(D.current!==t&&(D.current=t,x.current&&v.current&&r)){const S=cs(v.current),T=cs(r),F=x.current.replace(S,T);d(F),m(!0),y(!1),C(0),k(q=>q+1),A.current=!1,w.current&&(clearTimeout(w.current),w.current=null);return}},[t,r]),ee(()=>{if(M){const S=M+"?width=600px";x.current=S,r&&(v.current=r),d(S),u(!1),m(!0)}},[M]),ee(()=>{const S=T=>{T.data.type==="codeyam-resize"&&(A.current||(A.current=!0,w.current&&(clearTimeout(w.current),w.current=null),C(0),y(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{m(!1)})})))};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]);const _=()=>{A.current=!1,w.current&&clearTimeout(w.current);const S=500*Math.pow(2,b);w.current=setTimeout(()=>{A.current||(b<2?(C(T=>T+1),k(T=>T+1),m(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),y(!0),m(!1)))},S)};return ee(()=>{s&&!g.current&&t&&e&&(g.current=!0,u(!0),y(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(T){console.error("[useInteractiveMode] Failed to clear log file:",T)}I(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,I,a]),ee(()=>{const S=e,T=()=>{if(g.current&&S){const q=new URLSearchParams({action:"stop",analysisId:S});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const J=navigator.sendBeacon("/api/interactive-mode",q);console.log("[useInteractiveMode] sendBeacon result:",J),J||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:q,keepalive:!0}).catch(U=>console.error("Failed to stop interactive mode:",U)))}},F=()=>{T()};return window.addEventListener("beforeunload",F),()=>{window.removeEventListener("beforeunload",F),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:S}),T()}},[e]),{interactiveServerUrl:c,isStarting:h,isLoading:p,showIframe:f,iframeKey:N,onIframeLoad:_}}const vn=10,pu=1024;function _o({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=P(null),h=Ne(null),u=re(()=>[...a].sort((b,C)=>b.width-C.width),[a]),{fittingPresets:p,overflowPresets:m}=re(()=>{const b=[],C=[];for(const N of u)N.width<=pu?b.push(N):C.push(N);return C.sort((N,k)=>k.width-N.width),{fittingPresets:b,overflowPresets:C}},[u]),f=oe(b=>{if(!h.current)return null;const C=h.current.getBoundingClientRect(),N=b-C.left,k=C.width,w=k/2,M=(p.length>0?p[p.length-1].width:0)/2,I=w-M,D=w+M,L=m.length>0?(m.length-1)*vn:0;if(m.length>0){if(N<I){if(N<=L){const S=Math.min(Math.floor(N/vn),m.length-1);return m[S]}return m[m.length-1]}if(N>D){const S=k-N;if(S<=L){const T=Math.min(Math.floor(S/vn),m.length-1);return m[T]}return m[m.length-1]}}const _=Math.abs(N-w);for(let S=p.length-1;S>=0;S--){const T=p[S],F=p[S-1],q=T.width/2,J=F?F.width/2:0;if(_<=q&&_>=J)return T}return p[0]||m[m.length-1]||null},[p,m]),y=oe(b=>{const C=f(b.clientX);d(C),s==null||s(C)},[f,s]),g=oe(()=>{d(null),s==null||s(null)},[s]),x=oe(b=>{const C=f(b.clientX);C&&r(C)},[f,r]),v=c||{name:t,width:e};return l("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map(b=>{const C=b.width===e,N=(c==null?void 0:c.name)===b.name,k=b.width/2;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${k}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${k}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((b,C)=>{const N=C*vn,k=b.width===e,w=(c==null?void 0:c.name)===b.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children: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:[v.name," - ",v.width,"px"]})})]})}function Mo({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=P(""),[i,c]=P(""),d=()=>{const u=s.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("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:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&s.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&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[n("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"}),n("button",{onClick:d,disabled:!s.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 To(e){const[t,r]=P([]),a=e?`codeyam-custom-sizes-${e}`:null;ee(()=>{if(!a||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(a);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[a]);const s=oe(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]),o=oe((c,d,h)=>{r(u=>{const p=u.findIndex(y=>y.name===c),m={name:c,width:d,height:h};let f;return p>=0?(f=[...u],f[p]=m):f=[...u,m],s(f),f})},[s]),i=oe(c=>{r(d=>{const h=d.filter(u=>u.name!==c);return s(h),h})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Un(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("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 ds=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],fu=80;function Wn(){const[e,t]=P(0);return ee(()=>{const r=setInterval(()=>{t(a=>(a+1)%ds.length)},fu);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:ds[e]})}async function gu({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw B("Invalid parameters",{status:400});const a=await Lt(t);if(!a)throw B("Entity not found",{status:404});const s=await sa(a),o=((c=s==null?void 0:s.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw B("Scenario not found",{status:404});const i=await $e();return B({entity:a,scenario:o,analysis:s,projectSlug:i})}const Pr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],yu=De(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Be(),o=Tt(),[i]=on(),[c,d]=P(null),[h,u]=P(1440),[p,m]=P({name:"Desktop",width:1440,height:900}),[f,y]=P(!1),[g,x]=P(null),{customSizes:v,addCustomSize:b}=To(s),C=re(()=>[...Pr,...v],[v]),{interactiveServerUrl:N,isStarting:k,isLoading:w,showIframe:A,iframeKey:M,onIframeLoad:I}=mn({analysisId:a==null?void 0:a.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:s,enabled:!0}),{lastLine:D}=gt(s,k||w),L=()=>{o(`/entity/${t.sha}`)},_=(H,V)=>{u(H);const ae=C.find(j=>j.width===H&&j.height===V);d(ae||null),m({name:(ae==null?void 0:ae.name)||"Custom",width:H,height:V})},S=H=>{d(H),u(H.width),m({name:H.name,width:H.width,height:H.height})},T=H=>{b(H,p.width,p.height??900),y(!1),m(V=>({...V,name:H}))},F=((a==null?void 0:a.scenarios)||[]).filter(H=>{var V;return!((V=H.metadata)!=null&&V.sameAsDefault)}),q=F.findIndex(H=>H.id===(r==null?void 0:r.id)),J=q+1,U=F.length,Y=q>0,z=q<F.length-1,$=()=>{if(Y){const H=F[q-1],V=encodeURIComponent(`/entity/${t.sha}/scenarios/${H.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${H.id}/fullscreen?from=${V}`)}},E=()=>{if(z){const H=F[q+1],V=encodeURIComponent(`/entity/${t.sha}/scenarios/${H.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${H.id}/fullscreen?from=${V}`)}},W=k||w||!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:[n("img",{src:qs,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:$,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[J,"/",U]}),n("button",{onClick:E,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:L,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),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:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Pr[Pr.length-1].width}px`,width:"100%"},children:n(_o,{currentViewportWidth:h,currentPresetName:p.name,onDevicePresetClick:S,devicePresets:C,hideLabel:!0,onHoverChange:x,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:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||p.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:p.name,onChange:H=>{const V=C.find(ae=>ae.name===H.target.value);V&&S(V)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[C.map(H=>n("option",{value:H.name,children:H.name},H.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:H=>{const V=parseInt(H.target.value,10);!isNaN(V)&&V>0&&_(V,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"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:p.height??900}),p.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
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:N?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[W&&n("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:[n("div",{className:"mb-4",children:n(Un,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),D&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Wn,{}),D]})]})]})}),n("iframe",{src:N,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:I,style:{opacity:A?1:0}},M)]}):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:[n("div",{className:"mb-4",children:n(Un,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),D&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Wn,{}),D]})]})]})}),f&&n(Mo,{width:p.width,height:p.height??900,onSave:T,onCancel:()=>y(!1)})]})}),xu=Object.freeze(Object.defineProperty({__proto__:null,default:yu,loader:gu},Symbol.toStringTag,{value:"Module"})),jo=Vr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),ca=()=>{const e=Gn(jo);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},ir=({children:e})=>{const[t,r]=P({height:720,width:1200}),[a,s]=P(1),[o,i]=P(1200),c=Ne(null),d=oe(({height:p,width:m})=>{r(f=>({height:p??f.height,width:m??f.width}))},[]),h=oe(p=>{s(p)},[]),u=oe(p=>{i(p)},[]);return n(jo.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:a,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},bu=typeof window<"u";function vu(){const[e,t]=P(null);return ee(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const wu=1200,Cu=720,us=30,Nu=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const h=vu(),[u,p]=P(!1),[m,f]=P(!1),[y,g]=P(wu),[x,v]=P(Cu),[b,C]=P(null),[N,k]=P(null),{dimensions:w,updateDimensions:A,iframeRef:M,updateScale:I,updateMaxWidth:D}=ca(),L=re(()=>Math.min(1,y/w.width),[y,w.width]),_=N!==null?N:L;ee(()=>{u||(I(_),c==null||c(_))},[_,I,c,u]),ee(()=>{D(y)},[y,D]);const S=oe(()=>{p(!0),k(L)},[L]),T=oe(()=>{p(!1),k(null)},[]),F=oe((z,$)=>{const E=N!==null?N:1,W=Math.round($.size.width/E);A({width:W}),d==null||d(W,w.height)},[A,N,d,w.height]),q=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ee(()=>{const z=$=>{if($.data.type==="codeyam-resize"){if(t&&$.data.name!==t||w.height===$.data.height||$.data.height===0)return;A({height:$.data.height})}};return window.addEventListener("message",z),()=>{window.removeEventListener("message",z)}},[M,t,a,w,A]),ee(()=>{m&&o&&o(M.current)},[m,o,M]),ee(()=>{if(!t)return;const z=setInterval(()=>{var $,E;(E=($=M==null?void 0:M.current)==null?void 0:$.contentWindow)==null||E.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(z)},[t,M]),ee(()=>{const z=()=>{const $=document.getElementById("scenario-container");if(!$)return;const E=$.getBoundingClientRect(),W=$.clientWidth-us*2,H=window.innerHeight-E.top-us*2,V=Math.max(H,400),ae=window.innerHeight-E.top;g(W),v(V),C(ae)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),ee(()=>{A({width:a,height:s})},[a,s,A]);const J=re(()=>w.width*_,[w.width,_]),U=re(()=>{const z=w.height,$=z*_;return z&&z!==720&&z!==900&&$<x?$:x},[w.height,x,_]),Y=oe(()=>{window.history.back()},[]);return!bu||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
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
- `}),n(h,{width:J,height:U,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:S,onResizeStop:T,onResize:F,children:n("div",{className:"overflow-auto",style:{width:`${J}px`,height:`${U}px`},children:n("div",{style:{width:`${w.width}px`,height:`${w.height}px`,transform:`scale(${_})`,transformOrigin:"top left"},children:r?n("iframe",{ref:M,className:"w-full h-full rounded-lg",src:r,onLoad:q,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:Y,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Su({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[h,u]=P(!1),[p,m]=P(String(r)),[f,y]=P(String(a)),[g,x]=P(!1),[v,b]=P(!1),C=Ne(null);ee(()=>{g||m(String(r))},[r,g]),ee(()=>{v||y(String(a))},[a,v]),ee(()=>{const _=S=>{C.current&&!C.current.contains(S.target)&&u(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const N=re(()=>{const _=e.find(T=>T.width===r&&T.height===a);if(_)return _.name;const S=t.find(T=>T.width===r&&T.height===a);return S?S.name:"Custom"},[e,t,r,a]),k=N==="Custom",w=_=>{o(_.width,_.height),u(!1)},A=_=>{const S=_.target.value;m(S);const T=parseInt(S,10);!isNaN(T)&&T>0&&o(T,a)},M=_=>{const S=_.target.value;y(S);const T=parseInt(S,10);!isNaN(T)&&T>0&&o(r,T)},I=()=>{x(!1);const _=parseInt(p,10);(isNaN(_)||_<=0)&&m(String(r))},D=()=>{b(!1);const _=parseInt(f,10);(isNaN(_)||_<=0)&&y(String(a))},L=_=>{(_.key==="Enter"||_.key==="Escape")&&_.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:C,children:[l("button",{onClick:()=>u(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:N}),n("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(he,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(_=>l("button",{onClick:()=>w(_),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${N===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:_.name}),l("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]},_.name))]}),t.length>0&&l(he,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((_,S)=>_.width-S.width).map(_=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>w(_),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:_.name}),l("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]}),c&&n("button",{onClick:S=>{S.stopPropagation(),N===_.name&&e.length>0&&o(e[0].width,e[0].height),c(_.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},_.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:p,onChange:A,onFocus:()=>x(!0),onBlur:I,onKeyDown:L,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:M,onFocus:()=>b(!0),onBlur:D,onKeyDown:L,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),s!==void 0&&s<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),k&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function _r(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const a of e)if(a.name===t||a.title===t||a.id===t)return a}return e[t]}function zr(e){return e&&(typeof e=="object"||Array.isArray(e))}function Eu(e){return Array.isArray(e)?e.length:void 0}function Au(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,s)=>s.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((s,o)=>{const i=zr(t[s]),c=zr(t[o]);return i&&!c?1:!i&&c?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function ku({scenarioFormData:e,handleInputChange:t}){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:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Pu({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=oe(()=>{s&&s(e)},[s,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:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Io=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Io||{});const _u=({name:e,value:t,options:r,onChange:a})=>{const s=oe(o=>{a({target:{name:e,value:o.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:s,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},Mu=({name:e,value:t,onChange:r})=>{const a=oe(s=>{const o=s.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange: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 Tu({dataType:e,path:t,value:r,onChange:a}){const s=re(()=>t[t.length-1],[t]),o=re(()=>t.join("-"),[t]),i=oe(d=>{a(t,d.target.value)},[a,t]),c=oe(d=>{a(t,d.target.value)},[a,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(_u,{name:o,value:r,options:e.split("|"),onChange:i}):e===Io.BOOLEAN?n(Mu,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function ju({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=P(!1),[c,d]=P(""),h=oe(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const p=e.scenarios.find(x=>x.name===t);if(!p)throw new Error("Scenario not found");const m=e.scenarios.find(x=>x.name===Xn),f=await s(c,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,v)=>{const b=Object.assign({},x);return g(x)&&g(v)&&Object.keys(v).forEach(C=>{g(v[C])?C in x?b[C]=y(x[C],v[C]):Object.assign(b,{[C]:v[C]}):Object.assign(b,{[C]:v[C]})}),b},g=x=>x&&typeof x=="object"&&!Array.isArray(x);p.metadata.data=y(y((m==null?void 0:m.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,r,t,a,s]),u=oe(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:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?l(he,{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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Iu({namedPath:e,path:t,last:r,onClick:a}){const s=oe(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:s,children:e[e.length-1]})}function $u({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),a=re(()=>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:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>l("div",{className:"flex items-center gap-1",children:[n(Iu,{namedPath:e.namedPath.slice(0,o+a+1),path:e.path.slice(0,o+a+1),last:o+a===e.namedPath.length-1,onClick:t}),o+a<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${s}-${o+a}`))]})}function hs({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=re(()=>r.data,[r]),h=re(()=>Au(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n($u,{dataItem:r,onClick:a}),l("div",{className:"flex flex-col gap-3",children:[n(ju,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,p)=>{var f;if(zr(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(Pu,{path:g,namedPath:x,isArray:Array.isArray(d),count:Eu(d[u]),onClick:a},`data-${u}-${p}`)}if(u==="id")return null;const m=[...r.path,u];return n(Tu,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:m,value:d[u],onChange:s},`InputField-${m.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("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"}),n("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)&&n("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 ms({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=P(r),c=[];return a&&c.push("border-t"),s&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const Ru=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:h})=>{const u=oe((A,M)=>{const I=Object.assign({},A),D=L=>L&&typeof L=="object"&&!Array.isArray(L);return D(A)&&D(M)&&Object.keys(M).forEach(L=>{D(M[L])?L in A?I[L]=u(A[L],M[L]):Object.assign(I,{[L]:M[L]}):Object.assign(I,{[L]:M[L]})}),I},[]),[p,m]=P({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=P(null),g=re(()=>({...p.data}),[p]),x=re(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=re(()=>{const A={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(A).reduce((M,I)=>{if(I.includes(".")){const[D,L]=I.split(".");M[D]||(M[D]={}),M[D][L]=A[I]}else M[I]=A[I];return M},{})},[r]),b=oe(async A=>{A.preventDefault();const M=A.target.querySelector('input[name="recapture"]'),I=(M==null?void 0:M.value)==="true",D={mockData:p.data.mockData??{},argumentsData:p.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:p.name,shouldRecapture:I,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 L=a==null?void 0:a.scenarios.map(_=>!s&&_.name===e.name?{..._,name:p.name,description:p.description,metadata:{..._.metadata,data:D}}:_);s&&L.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:",L),o&&await o(L,{recapture:I}),i&&i(p.name)},[a,e.name,p,g,s,o,i]),C=oe(A=>{m(M=>({...M,[A.target.name]:A.target.value}))},[]),N=oe(A=>{y(M=>{if(!M)return null;for(const I of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let D=I;for(const L of M.path)if(D=_r(D,L),!D)break;D&&(M.data=D)}return{...M}}),m({name:A.name,description:A.description,data:A.metadata.data})},[]),k=oe((A,M)=>{m(I=>{for(const D of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let L=D;for(const _ of A.slice(0,-1))if(L=_r(L,_),!L)break;if(L){const _=L[A[A.length-1]];y(S=>S?(S.namedPath[S.namedPath.length-1]===_&&(S.namedPath[S.namedPath.length-1]=M.toString()),S.data[A[A.length-1]]=M,{...S}):null),L[A[A.length-1]]=M}}return{...I}})},[]),w=oe(A=>{var L,_,S;if(A.length===0){y(null);return}let M=x;const I=[];let D=v;for(const T of A){if(I.push(isNaN(parseInt(T))?T:((L=M[T])==null?void 0:L.name)??((_=M[T])==null?void 0:_.title)??((S=M[T])==null?void 0:S.id)??T),M=_r(M,T),!M){console.log("Data not found",M,T),y(null);return}Array.isArray(D)?D=D[0]:D=D[T]}y({path:A,namedPath:I,data:M,structure:D})},[x,v]);return ee(()=>{const A=M=>{var I;M.data.type==="codeyam-log"&&((I=M.data.data)!=null&&I.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",M.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),ee(()=>{var A;if((A=c==null?void 0:c.current)!=null&&A.contentWindow){const M={arguments:g.argumentsData??[],...g.mockData??{}},I={type:"codeyam-override-data",name:e.name,data:JSON.stringify(M)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:I.type,name:I.name,dataPreview:JSON.stringify(M).substring(0,200)+"...",fullData:M}),c.current.contentWindow.postMessage(I,"*")}},[g,e,c]),n("form",{method:"post",onSubmit:A=>void b(A),children:f?n(hs,{analysis:a,scenarioName:p.name,dataItem:f,onClick:w,onChange:k,onAIResult:N,onGenerateData:d,saveFeedback:h}):l(he,{children:[n(ms,{title:"Edit Name and Description",borderT:!0,children:n(ku,{scenarioFormData:p,handleInputChange:C})}),e.metadata.data&&n(ms,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(hs,{analysis:a,scenarioName:p.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:w,onChange:k,onAIResult:N,onGenerateData:d,saveFeedback:h})})]})})};function lr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:p=1440,defaultHeight:m=900,retryCount:f=0}){const{lastLine:y}=gt(u??null,a||s);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Nu,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:p,defaultHeight:m,onIframeLoad:c,onScaleChange:d,onDimensionChange:h},i)}),!o&&(a||s)&&n("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:[n("div",{className:"mb-4",children:n(Un,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Wn,{}),y]})]})]})})]}):n("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:[n("div",{className:"mb-4",children:n(Un,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Wn,{}),y]})]})]})})}const Du=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Lu({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await tr(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(d=s.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(h=s.scenarios)==null?void 0:h.find(u=>u.name===Xn),c=await $e();return B({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function Fu(){var T,F,q;const e=Be(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=Tt(),{iframeRef:c}=ca(),[d,h]=P(!1),[u,p]=P(null),[m,f]=P(null),[y,g]=P(!1),[x,v]=P(!1),[b,C]=P(null),{interactiveServerUrl:N,isStarting:k,isLoading:w,showIframe:A,iframeKey:M,onIframeLoad:I}=mn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),D=oe(async(J,U)=>{h(!0),p(null),f(null),console.log("[EditScenario] Starting save with options:",U),console.log("[EditScenario] Scenarios to save:",J);try{const Y={analysis:t,scenarios:J};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:J.length,scenarioNames:J.map(E=>E.name)});const z=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}),$=await z.json();if(console.log("[EditScenario] API response:",$),!z.ok||!$.success)throw new Error($.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),U!=null&&U.recapture&&r.id&&N){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:N}),p("Changes saved. Capturing screenshot...");const E={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",E);const W=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});console.log("[EditScenario] Capture response status:",W.status);const H=await W.json();if(console.log("[EditScenario] Capture response body:",H),!W.ok||!H.success)throw console.error("[EditScenario] Capture failed:",H),new Error(H.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",H),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),p("Recapture successful")}else if(U!=null&&U.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const E=new FormData;E.append("analysisId",t.id||""),E.append("scenarioId",r.id||"");const W=await fetch("/api/recapture-scenario",{method:"POST",body:E}),H=await W.json();if(!W.ok||!H.success)throw new Error(H.error||"Failed to trigger recapture");console.log("Recapture queued:",H),f(H.jobId),p("Changes saved. Screenshot recapture queued.")}else p("Changes saved successfully.")}catch(Y){console.error("Error saving scenarios:",Y),p(`Error: ${Y instanceof Error?Y.message:String(Y)}`)}finally{h(!1)}},[t,r.id,N]),L=oe(J=>{},[]),_=oe(async(J,U)=>{var $;const Y=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:J,existingScenarios:t.scenarios,scenariosDataStructure:($=t.metadata)==null?void 0:$.scenariosDataStructure,editingMockName:r.name,editingMockData:U==null?void 0:U.data})}),z=await Y.json();if(!Y.ok||!z.success)throw new Error(z.error||"Failed to generate scenario data");return z.data},[t,r.name]),S=oe(async()=>{var J;if(!r.id){C("Cannot delete scenario without ID");return}g(!0),C(null);try{const U=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((J=r.metadata)==null?void 0:J.screenshotPaths)||[]})}),Y=await U.json();if(!U.ok||!Y.success)throw new Error(Y.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(U){console.error("[EditScenario] Error deleting scenario:",U),C(U instanceof Error?U.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,(T=r.metadata)==null?void 0:T.screenshotPaths,s,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:[n("div",{className:"mb-4",children:l(se,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(F=t.entity)==null?void 0:F.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),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:[n(Ru,{currentScenario:r,defaultScenario:a,dataStructure:((q=t.metadata)==null?void 0:q.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:D,onNavigate:L,iframeRef:c,onGenerateData:_,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(se,{to:`/entity/${s}`,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:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?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 "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void S(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>v(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(lr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:k,isLoading:w,showIframe:A,iframeKey:M,onIframeLoad:I,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Ou=De(function(){return n(ir,{children:n(Fu,{})})}),zu=Object.freeze(Object.defineProperty({__proto__:null,default:Ou,loader:Lu,meta:Du},Symbol.toStringTag,{value:"Module"}));function Yu({executionFlows:e,selections:t,onChange:r,disabled:a=!1}){const s=oe(i=>t.some(c=>c.flowId===i),[t]),o=oe(i=>{s(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,s]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=s(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:[n("input",{type:"checkbox",checked:c,onChange:()=>o(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:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((h,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",n("span",{className:"text-gray-400",children:h.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function da(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;r.forEach(d=>{a.set(d.id,d)});const s=[];t.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(p=>{const m=a.get(p);m&&m.usedInScenarios.push({id:d.id||"",name:d.name})}),s.push({scenario:d,coveredFlowIds:h})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:s}}function Bu(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Uu=({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 Wu({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await tr(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=(i=a.scenarios)==null?void 0:i.find(c=>c.name===Xn);if(!s)throw new Response("Default scenario not found",{status:404});const o=await $e();return B({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function Hu(){var Y;const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Be(),o=Tt(),{iframeRef:i}=ca(),[c,d]=P(""),[h,u]=P(400),[p,m]=P(!1),[f,y]=P(!1),[g,x]=P(!1),[v,b]=P(null),[C,N]=P(null),[k,w]=P([]),A=re(()=>{var $;return!(($=e==null?void 0:e.metadata)!=null&&$.executionFlows)||!(e!=null&&e.scenarios)?[]:da(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:M,isStarting:I,isLoading:D,showIframe:L,iframeKey:_,onIframeLoad:S}=mn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:s,enabled:!0}),T=oe(async()=>{var z,$,E,W;if(!c.trim()&&k.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),N("Generating scenario with AI...");try{const H=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(z=e.metadata)==null?void 0:z.scenariosDataStructure,flowSelections:k.length>0?k:void 0})}),V=await H.json();if(!H.ok||!V.success)throw new Error(V.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",V.data);const ae=V.data;if(!ae.name||!ae.data)throw new Error("AI response missing required fields (name or data)");N("Saving new scenario..."),x(!0);const O={name:ae.name,description:ae.description||c,metadata:{data:ae.data,interactiveExamplePath:($=t.metadata)==null?void 0:$.interactiveExamplePath}},j=[...e.scenarios||[],O],R=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:j})}),G=await R.json();if(!R.ok||!G.success)throw new Error(G.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",G);const te=(W=(E=G.analysis)==null?void 0:E.scenarios)==null?void 0:W.find(ce=>ce.name===ae.name);if(!(te!=null&&te.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),N("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(M){N("Capturing screenshot...");const ce=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:M,scenarioId:te.id,projectId:e.projectId,viewportWidth:1440})}),pe=await ce.json();!ce.ok||!pe.success?(console.error("[CreateScenario] Capture failed:",pe),N("Scenario created! (Screenshot capture failed)")):N("Scenario created and captured!")}else N("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${te.id}`)},1e3)}catch(H){console.error("[CreateScenario] Error:",H),b(H instanceof Error?H.message:String(H)),N(null)}finally{y(!1),x(!1)}},[c,k,e,t,a,M,o]),F=f||g,q=oe(()=>{m(!0)},[]),J=oe(z=>{if(!p)return;const $=z.clientX;$>=250&&$<=600&&u($)},[p]),U=oe(()=>{m(!1)},[]);return ee(()=>(p?(document.addEventListener("mousemove",J),document.addEventListener("mouseup",U)):(document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",U)),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",U)}),[p,J,U]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("button",{onClick:()=>void o(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(se,{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",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((Y=e==null?void 0:e.scenarios)==null?void 0:Y.length)||0})]})}),n(se,{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"}),n(se,{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"}),n(se,{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"}),n(se,{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:`${h}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),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"," ",k.length>0&&l("span",{className:"text-blue-600",children:["(",k.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Yu,{executionFlows:A,selections:k,onChange:w,disabled:F})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:z=>d(z.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:F})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void T(),disabled:F||!c.trim()&&k.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:F?"Creating...":"Create Scenario"}),C&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:C}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),l("div",{onMouseDown:q,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:p?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
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:n(lr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:M,isStarting:I,isLoading:D,showIframe:L,iframeKey:_,onIframeLoad:S,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Vu=De(function(){return n(ir,{children:n(Hu,{})})}),Ju=Object.freeze(Object.defineProperty({__proto__:null,default:Vu,loader:Wu,meta:Uu},Symbol.toStringTag,{value:"Module"}));var le;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(le||(le={}));function $o(e,t){return e?Object.values(le.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Ro=$o(process.env.DEFAULT_SMALLER_MODEL,le.Model.OPENAI_GPT4_1_MINI),Gu=$o(process.env.DEFAULT_LARGER_MODEL,le.Model.OPENAI_GPT4_1),Qe={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Mr={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},qu={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Tr={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},ut={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Ku={[le.Model.OPENAI_GPT5_1]:{id:le.Model.OPENAI_GPT5_1,provider:Qe,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[le.Model.OPENAI_GPT5]:{id:le.Model.OPENAI_GPT5,provider:Qe,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT5_MINI]:{id:le.Model.OPENAI_GPT5_MINI,provider:Qe,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT5_NANO]:{id:le.Model.OPENAI_GPT5_NANO,provider:Qe,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT4_1]:{id:le.Model.OPENAI_GPT4_1,provider:Qe,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[le.Model.OPENAI_GPT4_1_MINI]:{id:le.Model.OPENAI_GPT4_1_MINI,provider:Qe,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[le.Model.OPENAI_GPT4_O]:{id:le.Model.OPENAI_GPT4_O,provider:Qe,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[le.Model.OPENAI_GPT4_O_MINI]:{id:le.Model.OPENAI_GPT4_O_MINI,provider:Qe,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[le.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:le.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Mr,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[le.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:le.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Mr,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[le.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:le.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Mr,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:le.Model.OPENAI_GPT_OSS_120B_GROQ,provider:qu,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[le.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:le.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:ut,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[le.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:le.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:ut,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[le.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:le.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:ut,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[le.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:le.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:ut,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[le.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:le.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:ut,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[le.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Tr,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[le.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Tr,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[le.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Tr,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[le.Model.PHIND_CODELLAMA]:{id:le.Model.PHIND_CODELLAMA,provider:Qe,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[le.Model.GOOGLE_GEMINI_PRO]:{id:le.Model.GOOGLE_GEMINI_PRO,provider:ut,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[le.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:le.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:ut,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[le.Model.META_CODELLAMA_34B_INSTRUCT]:{id:le.Model.META_CODELLAMA_34B_INSTRUCT,provider:ut,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[le.Model.OPENAI_GPT4_PREVIEW]:{id:le.Model.OPENAI_GPT4_PREVIEW,provider:Qe,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function cr(e){const t=Ku[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Qu(e){return cr(e).maxCompletionTokens}function Zu(e){return cr(e).pricing}const ps=1e6;function Xu({model:e,usage:t}){const r=Zu(e);return r?t.prompt_tokens*(r.input/ps)+t.completion_tokens*(r.output/ps):null}function eh({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const a=t.usage||{prompt_tokens:0,completion_tokens:0},s=Xu({model:r,usage:a});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:s?Math.round(s*1e5)/1e5:void 0}}function th({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??Ro,i=cr(o);Qu(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format:a==="json_schema"&&s?{type:"json_schema",json_schema:{name:s.name,schema:s.schema,strict:s.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Yr="/tmp/codeyam-e2e-tracking";let jr,Ir;function nh(){return jr===void 0&&(jr=process.env.CODEYAM_E2E_TRACK_DATA==="true"),jr}function rh(){return Ir===void 0&&(Ir=!process.env.CODEYAM_LLM_FIXTURES_DIR),Ir}function ah(){K.existsSync(Yr)||K.mkdirSync(Yr,{recursive:!0})}function sh(e){const t=JSON.stringify(e,null,0);return vl.createHash("md5").update(t).digest("hex")}function oh(e,t,r){return[e].join("_")+".json"}function Do(e,t,r,a){if(!nh())return;ah();const s=oh(e),o=Z.join(Yr,s),i=sh(t);if(rh()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:a,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const c=JSON.parse(K.readFileSync(o,"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=Br(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const h=o.replace(".json","_DIFF.json");K.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:r,scenarioName:a,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Br(e,t,r=""){const a=[];if(typeof e!=typeof t)return a.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),a;if(e===null||t===null)return e!==t&&a.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),a;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&a.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const s=Math.max(e.length,t.length);for(let o=0;o<s;o++)a.push(...Br(e[o],t[o],`${r}[${o}]`));return a}if(typeof e=="object"&&typeof t=="object"){const s=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...s,...o]));for(const c of i){const d=e[c],h=t[c];c in e?c in t?a.push(...Br(d,h,`${r?r+".":""}${c}`)):a.push(`${r?r+".":""}${c}: missing in second run`):a.push(`${r?r+".":""}${c}: missing in first run`)}return a}if(e!==t){const s=JSON.stringify(e),o=JSON.stringify(t);s.length<100&&o.length<100?a.push(`${r||"root"}: ${s} vs ${o}`):a.push(`${r||"root"}: values differ (${s.length} chars vs ${o.length} chars)`)}return a}Zr(Qr);const wn=new kl({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),fs={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},ht={};async function Ur({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=Ro,attempts:i=0}){var w,A,M,I,D,L,_;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ih(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${wn.size}, running=${wn.pending}]`);const c=Date.now();let d,h=0;const u=cr(o),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 m=new Al({apiKey:p,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},y=th(f),g=await wn.add(()=>(d=Date.now(),es(async()=>{const S=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],F=setInterval(()=>{const q=Math.floor((Date.now()-S)/1e3),J=Math.floor(q/10)%T.length;ns(1,`${T[J]} [type=${e}, model=${o}, elapsed=${q}s]`)},1e4);try{return await m.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(F)}},{...fs,onFailedAttempt:S=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:S,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})),{throwOnTimeout:!0}),x=Date.now(),v=eh({chatRequest:f,chatCompletion:g,model:o});if(!v)throw new Error("Failed to get LLM call stats");v.retries=h,v.wait_ms=d-c,v.duration_ms=x-c;const b=(w=g.choices)==null?void 0:w[0];let C=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");C=(A=b.message)==null?void 0:A.content}let N=C;C&&(N=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=a?N&&(((M=N.match(/\{[\s\S]*\}/))==null?void 0:M[0])??N):N;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:C,chatCompletion:g,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Ur({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(k.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:C,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(k)}catch(S){if(console.log("CodeYam Error: Invalid JSON in completion",{error:S.message,model:o,completion:k.substring(0,500),rawCompletion:C==null?void 0:C.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:S.message});const T=`Your previous response contained invalid JSON with the following error:
110
-
111
- ${S.message}
112
-
113
- Here was your previous response:
114
- \`\`\`
115
- ${k}
116
- \`\`\`
117
-
118
- Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,F=await wn.add(()=>es(async()=>{const Y=Date.now(),z=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],$=setInterval(()=>{const E=Math.floor((Date.now()-Y)/1e3),W=Math.floor(E/10)%z.length;ns(1,`${z[W]} [type=${e}, model=${o}, elapsed=${E}s]`)},1e4);try{return await m.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:k},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval($)}},{...fs,onFailedAttempt:Y=>{console.log("CodeYam Error: Correction call failed",{error:Y,attempts:i})}}),{throwOnTimeout:!0}),q=(L=(D=(I=F.choices)==null?void 0:I[0])==null?void 0:D.message)==null?void 0:L.content;let J=q;q&&(J=q.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const U=J&&(((_=J.match(/\{[\s\S]*\}/))==null?void 0:_[0])??J);if(!U)throw new Error("Correction attempt returned empty completion");try{JSON.parse(U),console.log("CodeYam: JSON correction successful");const Y=Date.now();return v.duration_ms=Y-c,{finishReason:F.choices[0].finish_reason,completion:U,stats:v}}catch(Y){return console.log("CodeYam Error: Corrected JSON still invalid",{error:Y.message,correctedCompletion:U.substring(0,500)}),await Ur({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${S.message}`)}return Do(`completionCall_${e}`,{completion:k,finishReason:g.choices[0].finish_reason}),{finishReason:g.choices[0].finish_reason,completion:k,stats:v}}async function ih(e,t,r){var o,i,c,d,h;const a=await import("fs"),s=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!a.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=a.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const p={};for(const b of u)try{const C=a.readFileSync(s.join(t,b),"utf-8"),N=JSON.parse(C);p[N.prompt_type]||(p[N.prompt_type]=[]),p[N.prompt_type].push(N)}catch(C){console.warn(`Failed to parse LLM fixture file ${b}:`,C)}for(const b of Object.keys(p))p[b].sort((C,N)=>{const k=C.created_at??0,w=N.created_at??0;return k-w});const m=p[e];if(!m||m.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)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),C=b==null?void 0:b[1];if(C){const N={};for(const w of m)try{const M=((o=JSON.parse(w.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";N[M]||(N[M]=[]),N[M].push(w)}catch{}const k=N[C];if(k&&k.length>0){const w=`${t}::${e}::${C}`;ht[w]===void 0&&(ht[w]=0);const A=ht[w];ht[w]=(A+1)%k.length,f=k[A],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${C}' [${A+1}/${k.length}]`)}else{const w=Object.keys(N).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${C}'. Available: [${w}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;ht[b]===void 0&&(ht[b]=0);const C=ht[b];ht[b]=(C+1)%m.length,f=m[C],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${C+1}/${m.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 x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((h=x.match(/\{[\s\S]*\}/))==null?void 0:h[0])??x);return Do(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",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 gs(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function lh(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=Vs(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let c;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?c=Z.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=Z.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=Z.dirname(c);return await Re.mkdir(u,{recursive:!0}),await Re.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=gs();if(!h)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 ${s} property ${u} with explicit value 'undefined'`);try{return await new Zn().send(new Pl({TableName:gs(),Item:Ml(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Zn({});new Zn({});new Zn({});const ch=3,dh=2,ua=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+ch*String(t).length*(1+dh)});new Xr(ua());new Xr(ua());new Xr(ua());class uh{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var a;return(a=this.byClassAndMethod.get(t))==null?void 0:a.get(r)}}class hh{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class mh{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class ph{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class fh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class gh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];if(a.addType(o,"function"),a.addEquivalence(o.withParameter(1),r.withElement("*")),s.args.length>1){const i=s.args[1];a.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class yh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class xh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.withReturnValues();a.addType(s,"unknown")}isComplete(){return!0}}class bh{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>2)for(let o=2;o<s.args.length;o++){const i=s.args[o];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class vh{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0)for(let o=0;o<s.args.length;o++)a.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class wh{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Ch{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Nh{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Sh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Eh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ah{getReturnType(){return"object"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"array")}}isComplete(){return!0}}class kh{getReturnType(){return"string[]"}addEquivalences(t,r,a){a.addType(r,"string"),a.addType(t,"string[]"),a.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Ph{getReturnType(){return"unknown"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class _h{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Mh{getReturnType(){return"array"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function Th(){const e=new uh;return e.register("filter",new hh,"Array"),e.register("map",new Ch,"Array"),e.register("flatMap",new Nh,"Array"),e.register("join",new wh,"Array"),e.register("find",new fh,"Array"),e.register("findLast",new Eh,"Array"),e.register("at",new Sh,"Array"),e.register("reduce",new gh,"Array"),e.register("concat",new yh,"Array"),e.register("slice",new xh,"Array"),e.register("splice",new bh,"Array"),e.register("push",new vh,"Array"),e.register("some",new mh,"Array"),e.register("every",new ph,"Array"),e.register("fromEntries",new Ah,"Object"),e.register("split",new kh,"String"),e.register("then",new Ph,"Promise"),e.register("useState",new Mh,"React"),e.register("useMemo",new _h,"React"),e}Th();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 jh=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Ih=new Set(["find","findLast","at","pop","shift"]),$h=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Rh=new Set([...jh,...Ih,...$h]),Dh=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Lh=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Fh=new Set([...Dh,...Lh]);[...Rh,...Fh];class Oh{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const s=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${o}${s}${r}`,JSON.stringify(a)):console.info(`${o}${s}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new Oh({enabled:!1});function Ct(e,t){const r={added:{},removed:{},changed:{}},a=new Set(Object.keys(e??{})),s=new Set(Object.keys(t??{}));for(const o of s)a.has(o)||(r.added[o]=t[o]);for(const o of a)s.has(o)||(r.removed[o]=e[o]);for(const o of a)s.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function zh(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function Cn(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Yh=0;class ha{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Yh,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,a){var d,h,u,p;if(!this.isEnabled())return;const s=this.traces.get(t);if(!s)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,a);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(a)),i={stage:r,timestamp:Date.now(),data:o},c=s.stages[s.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:Ct(c.data.signatureSchema,o.signatureSchema),returnValueSchema:Ct(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const m=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of m){const y=(d=c.data.dependencySchemas)==null?void 0:d[f],g=(h=o.dependencySchemas)==null?void 0:h[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const v=`${f}::${x}`,b=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,C=(p=g==null?void 0:g[x])==null?void 0:p.returnValueSchema,N=Ct(b,C);zh(N)&&(i.diffFromPrevious.dependencySchemas[v]=N)}}}s.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const a=this.traces.get(t);a&&a.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}flush(){var d;if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(h=>`${h}(${this.traces.get(h).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const a={},s=new Map;for(const[h,u]of this.traces){let p=0;for(const m of u.stages){if(!m.diffFromPrevious)continue;const y=`${((d=u.stages[u.stages.indexOf(m)-1])==null?void 0:d.stage)??"start"}→${m.stage}`;if(a[y]||(a[y]={added:0,removed:0,changed:0}),m.diffFromPrevious.signatureSchema){const g=m.diffFromPrevious.signatureSchema;a[y].added+=Object.keys(g.added).length,a[y].removed+=Object.keys(g.removed).length,a[y].changed+=Object.keys(g.changed).length,p+=Cn(g)}if(m.diffFromPrevious.returnValueSchema){const g=m.diffFromPrevious.returnValueSchema;a[y].added+=Object.keys(g.added).length,a[y].removed+=Object.keys(g.removed).length,a[y].changed+=Object.keys(g.changed).length,p+=Cn(g)}}s.set(h,p)}const o=[...s.entries()].sort((h,u)=>u[1]-h[1]).slice(0,10).map(([h])=>h),i={meta:{timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},summary:{stageChangeCounts:a,entitiesWithMostChanges:o},entities:Object.fromEntries(this.traces)},c=Z.dirname(this.outputPath);K.existsSync(c)||K.mkdirSync(c,{recursive:!0}),K.writeFileSync(this.outputPath,JSON.stringify(i,null,2)),this.log(`flush: wrote trace to ${this.outputPath}`)}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),a=JSON.parse(r),s=new ha({enabled:!1});s.projectSlug=a.meta.projectSlug;for(const[o,i]of Object.entries(a.entities))s.traces.set(o,i);return s}getSummary(){var s,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let h=0;for(let u=1;u<d.stages.length;u++){const p=d.stages[u],f=`${((s=d.stages[u-1])==null?void 0:s.stage)??"start"}→${p.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=p.diffFromPrevious)!=null&&o.signatureSchema){const y=p.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=Cn(y)}if((i=p.diffFromPrevious)!=null&&i.returnValueSchema){const y=p.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=Cn(y)}}r.set(c,h)}const a=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:a}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(a=>({stage:a.stage,diffFromPrevious:a.diffFromPrevious?{signatureSchema:a.diffFromPrevious.signatureSchema,returnValueSchema:a.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const a=this.traces.get(t);return a?r?a.operations.filter(s=>s.path&&r.test(s.path)):a.operations:[]}tracePath(t,r){var o,i;const a=this.traces.get(t),s=[];if(!a)return{entityName:t,path:r,history:s};for(const c of a.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],h=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??h;u!==void 0&&s.push({stage:c.stage,value:u})}for(const c of a.operations)c.path===r&&s.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:s}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const a=this.traces.get(t);if(!a)return[];const s=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of a.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[h,u]of Object.entries(d))for(const[p,m]of Object.entries(u.returnValueSchema??{}))o.test(p)&&s.push({stage:i.stage,path:`${c}/${h}::${p}`,type:m,schemaType:"dependency"})}return s}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let a=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){a=r.stages[d];break}if(!a)return[];const s=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,h)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const p=u[1],m=u[2]==="[]";if(s.has(p))return;const f=p+(m?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:h})};for(const[,d]of Object.entries(a.data.dependencySchemas??{}))for(const[,h]of Object.entries(d))for(const[u,p]of Object.entries(h.returnValueSchema??{}))i(u,p);const c=[];for(const[d,h]of o)new Set(h.map(p=>p.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:h.map(p=>({...p,stage:a.stage}))});return c.sort((d,h)=>{const u=new Set(d.paths.map(m=>m.type)).size;return new Set(h.paths.map(m=>m.type)).size-u}),c}getStageDiffSummary(t,r,a){const s=this.traces.get(t);if(!s)return null;const o=s.stages.find(m=>m.stage===r),i=s.stages.find(m=>m.stage===a);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},h=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),p=new Set(Object.keys(h));for(const m of p)u.has(m)?d[m]!==h[m]&&c.typeChanged.push({path:m,from:d[m],to:h[m]}):c.added.push(`${m}: ${h[m]}`);for(const m of u)p.has(m)||c.removed.push(`${m}: ${d[m]}`);return c}traceSchemaTransform(t,r,a,s,o){if(!this.enabled)return s(a),a;const i={...a};s(a);const c=Ct(i,a);for(const[d,h]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:h,context:{...o,changeType:"added"}});for(const[d,h]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:h,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:h,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:h,after:u,context:{...o,changeType:"changed"}});return a}traceSchemaTransformResult(t,r,a,s,o){if(!this.enabled)return;const i=Ct(a,s);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:h}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:h,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,a,s,o="both"){if(!this.enabled){for(const i in a)for(const c in a[i]){const d=a[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&s(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&s(d.returnValueSchema)}return}for(const i in a)for(const c in a[i]){const d=a[i][c],h={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,s,{...h,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,s,{...h,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,a,s){var i;if(!this.enabled){s();return}const o={};for(const c in a){o[c]={};for(const d in a[c]){const h=a[c][d];o[c][d]={sig:{...h.signatureSchema||{}},rv:{...h.returnValueSchema||{}}}}}s();for(const c in a)for(const d in a[c]){const h=a[c][d],u=(i=o[c])==null?void 0:i[d],p={filePath:c,dependencyName:d};if(h.signatureSchema){const m=(u==null?void 0:u.sig)||{},f=Ct(m,h.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...p,schemaType:"signature",changeType:"changed"}})}if(h.returnValueSchema){const m=(u==null?void 0:u.rv)||{},f=Ct(m,h.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...p,schemaType:"returnValue",changeType:"changed"}})}}}}function Bh(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const ys=new ha({enabled:Bh(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{ys.isEnabled()&&ys.flush()});function Lo(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return _l.parse(e)}catch(r){const s=r.message.match(/invalid character .* at (\d+):(\d+)/);if(s){const o=parseInt(s[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),Lo(e)}return null}}function Uh({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:a}){let s="";return a&&a.length>0&&(s=`
119
- User-selected Execution Flow Values:
120
- The user has specifically requested these values be used in the scenario:
121
- ${a.map(o=>` - ${o.path}: ${o.value}${o.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(r,null,2)}
128
- \`\`\`
129
- Existing Mock Scenario Data:
130
- \`\`\`
131
- ${JSON.stringify(t,null,2)}
132
- \`\`\`
133
- ${s}
134
- New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
135
- `}function Wh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===Xn);return`Mock Scenario Data Structure:
136
- \`\`\`
137
- ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
138
- \`\`\`
139
-
140
- Existing Mock Scenario Data:
141
- \`\`\`
142
- ${JSON.stringify(a.map(i=>({name:i.name,data:Kt(o.metadata.data,i.metadata.data)})),null,2)}
143
- \`\`\`
144
-
145
- Mock Scenario that should be edited: "${t}"
146
- ${r?`The portion of the data that should be edited:
147
- \`\`\`
148
- ${JSON.stringify(r,null,2)}
149
- \`\`\``:""}
150
-
151
- How this data should be changed: "${e}"
152
- `}async function Hh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,flowSelections:o,model:i}){const c=t?Wh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):Uh({description:e,existingScenarios:a,scenariosDataStructure:s,flowSelections:o}),d=await Ur({type:"guessScenarioDataFromDescription",systemMessage:t?Jh(r):Vh,prompt:c,model:i??Gu});await lh({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:h}=d;return h?Lo(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Vh=`
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
- `,Jh=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 Gh({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return B({error:"Missing required field: description or flowSelections"},{status:400});const d=await Hh({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}),h=(d==null?void 0:d.data)||d;return B({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),B({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const qh=Object.freeze(Object.defineProperty({__proto__:null,action:Gh},Symbol.toStringTag,{value:"Module"}));async function Kh(e,t){const r=ge();if(!r)return{entityCalls:[],analysisCalls:[]};const a=Z.join(r,".codeyam","llm-calls");try{await Re.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const c=(await Re.readdir(a)).filter(v=>v.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],p=[];for(const v of c)v.startsWith(d)||h&&v.startsWith(h)?u.push(v):p.push(v);const m=u.map(async v=>{try{const b=Z.join(a,v),C=await Re.readFile(b,"utf-8");return JSON.parse(C)}catch{return null}}),f=p.map(async v=>{try{const b=Z.join(a,v),C=await Re.readFile(b,"utf-8"),N=JSON.parse(C);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(m),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?s.push(v):t&&v.object_id===t&&o.push(v);s.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function Qh({params:e,request:t}){const{entitySha:r}=e;if(!r)return B({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Kh(r,s);return B(o)}const Zh=Object.freeze(Object.defineProperty({__proto__:null,loader:Qh},Symbol.toStringTag,{value:"Module"}));function Xh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Me("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return em(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function em(e){const t=e.trim().split(`
190
- `).filter(a=>a.length>0),r=[];for(const a of t){const s=a[0],o=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),c,d=!1,h;if(s==="A"||o==="A")c="added",d=s==="A";else if(s==="M"||o==="M")c="modified",d=s==="M";else if(s==="D"||o==="D")c="deleted",d=s==="D";else if(s==="R"||o==="R"){c="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=ie.join(u,i);try{const m=(y,g)=>{const x=Pt.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const C=ie.join(y,b.name),N=ie.relative(u,C);b.isDirectory()?v.push(...m(C,g)):b.isFile()&&v.push(N)}return v},f=m(p,u);for(const y of f)r.push({path:y,status:c,staged:d,...h&&{oldPath:h}})}catch(m){console.error(`Failed to expand directory ${i}:`,m)}}else r.push({path:i,status:c,staged:d,...h&&{oldPath:h}})}return r}function tm(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function nm(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Me('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return Me("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Me("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function rm(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
191
- `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Fo(){const e=ge();return e?Xh(e):[]}function am(){const e=ge();return e?tm(e):null}function sm(){const e=ge();return e?nm(e):"main"}function om(){const e=ge();return e?rm(e):[]}function Oo(e,t){const r=ge();return r?im(e,t,r):[]}function im(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${t}`,{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 h=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],h=c[2]):p="modified",{path:h,status:p,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function lm(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=Pt.readFileSync(ie.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),s=""}return{oldContent:a,newContent:s,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 cm(e){const t=ge();return t?lm(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function dm(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Me(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Pn(e,t,r){const a=ge();return a?dm(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function xs(e,t){var r,a;try{return((a=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:a.trim())??null}catch(s){return console.error(`Failed to get commit SHA for ${e}:`,s),""}}function um(e,t,r,a){const s=qn.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function zo(){const e=ge();if(!e)throw new Error("No project root found");const t=ie.join(e,".codeyam","cache","branch-entity-diff");return Pt.existsSync(t)||Pt.mkdirSync(t,{recursive:!0}),t}function hm(e){try{const t=zo(),r=ie.join(t,`${e}.json`);if(!Pt.existsSync(r))return null;const a=Pt.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function mm(e,t){try{const r=zo(),a=ie.join(r,`${e}.json`);Pt.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function pm(e,t,r){const a=Dn(t,e),s=Dn(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),c=[],d=[],h=[];for(const[u,p]of i){const m=o.get(u);m?m.sha!==p.sha&&d.push({name:u,baseSha:m.sha,compareSha:p.sha,entityType:p.entityType}):c.push(p)}for(const[u,p]of o)i.has(u)||h.push(p);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:h}}function fm(e,t){const r=ge();if(!r)throw new Error("No project root found");const a=xs(e,r),s=xs(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=um(e,t,a,s),i=hm(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=Oo(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const p=Pn(u.path,e,t),m=Dn(p.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:m})}else if(u.status==="added"){const p=Pn(u.path,e,t),m=Dn(p.newContent,u.path);d.push({filePath:u.path,newEntities:m,modifiedEntities:[],deletedEntities:[]})}else{const p=Pn(u.path,e,t),m=pm(u.path,p.oldContent,p.newContent);(m.newEntities.length>0||m.modifiedEntities.length>0||m.deletedEntities.length>0)&&d.push(m)}const h={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return mm(o,h),h}function gm({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return B({error:"Missing required parameters: base and compare"},{status:400});const s=fm(r,a);return B(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),B({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const ym=Object.freeze(Object.defineProperty({__proto__:null,loader:gm},Symbol.toStringTag,{value:"Module"}));async function xm({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:s,viewportWidth:o=1440}=t;if(!r||!a||!s)return B({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=ge();if(!i)return B({error:"Project root not found"},{status:500});const c=Z.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),h=await new Promise(m=>{const f=Z.join(i,".codeyam","db.sqlite3"),y=Kn("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",v=>{const b=v.toString();g+=b;const C=b.trim().split(`
193
- `);for(const N of C)N.includes("[Capture]")&&console.log(N)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{m(v===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${v}`})}),y.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),m({success:!1,output:"",error:v.message})})});if(!h.success)return B({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return B({error:"Failed to parse capture result"},{status:500});const p=JSON.parse(u[1]);return B(p)}catch(t){return console.error("[Capture] Error:",t),B({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const bm=Object.freeze(Object.defineProperty({__proto__:null,action:xm},Symbol.toStringTag,{value:"Module"}));async function vm(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Le();const a=await lt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ke(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!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 Ft(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=ge();if(!d)throw new Error("Project root not found");const h=Z.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(h,"utf8")),{projectSlug:p}=u;if(!p)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:p,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${m}`),{jobId:m}}async function wm(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Le();const a=await lt({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 s=(u=a.scenarios)==null?void 0:u.find(p=>p.id===t);if(!s)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${s.name}`),await Ft(e,p=>{if(p&&(p.readyToBeCaptured=!0,delete p.finishedAt,p.scenarios)){const m=p.scenarios.find(f=>f.name===s.name);m&&(delete m.finishedAt,delete m.startedAt,delete m.error,delete m.errorStack,delete m.screenshotStartedAt,delete m.screenshotFinishedAt,delete m.interactiveStartedAt,delete m.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${s.name} for recapture`);const o=ge();if(!o)throw new Error("Project root not found");const i=Z.join(o,".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:h}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function Cm({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await dt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return B({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await wm(s,o,r);return console.log("[API] Scenario recapture queued",i),B({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),B({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Nm=Object.freeze(Object.defineProperty({__proto__:null,action:Cm},Symbol.toStringTag,{value:"Module"})),Sm=/<system-reminder>[\s\S]*?<\/system-reminder>/g,bs=2e3;function Em(){return`/private/tmp/claude-501/-${(ge()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Am="/tmp/claude-rule-markers";function km(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),a=String(t.path||"");return a?`"${r}" in ${a}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const Pm=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function _m(e){const t=[],r=new Set;for(const a of e)if(!(a.type!=="tool_call"||!a.name||!a.input)){if(a.name==="Write"||a.name==="Edit"){const s=String(a.input.file_path||"");if(s.includes(".claude/rules/")){const o=s.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${a.name}:${o}`;r.has(i)||(r.add(i),a.name==="Write"?t.push({action:"created",filePath:o,content:String(a.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(a.input.old_string||""),newString:String(a.input.new_string||"")}))}}else if(a.name==="Bash"){const s=String(a.input.command||"");if(s.includes("codeyam memory touch")){const o=`touch:${s}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:s}))}}}return t}function Mm(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let a=e.slice(r+t.length).trim();const s=a.indexOf(`
194
- ###`);return s!==-1&&(a=a.slice(0,s).trim()),a||void 0}function Tm(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const a of Pm)if(r.includes(a))return!0}return!1}function jm(e){const t=[],r={};for(const a of e){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,h=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:h,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const p=u,m=String(p.tool_use_id||"");let f=p.content;const y=!!p.is_error;typeof f=="string"&&(f=f.replace(Sm,"").trim()),t.push({type:"tool_result",tool_use_id:m,tool_name:r[m]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:h})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const p=u;if(p.type==="text"){const m=String(p.text||"").trim();m&&t.push({type:"assistant_text",text:m,timestamp:h})}else if(p.type==="tool_use"){const m=String(p.id||""),f=String(p.name||"unknown"),y=p.input||{};r[m]=f,t.push({type:"tool_call",tool_use_id:m,name:f,input:y,timestamp:h})}}}return t}function Im(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}async function $m({request:e}){var t;try{const a=((t=new URL(e.url).searchParams.get("search"))==null?void 0:t.toLowerCase())||"",s=Em(),o=Am,i=[];if(rt(s)){const d=await Za(s);for(const h of d)if(h.endsWith(".output")){const u=ie.join(s,h),p=await Xa(u);i.push({filePath:u,stem:h.replace(".output",""),mtime:p.mtimeMs})}}if(rt(o)){const d=await Za(o);for(const h of d)if(h.endsWith(".log")){const u=ie.join(o,h),p=await Xa(u);i.push({filePath:u,stem:h.replace(".log",""),mtime:p.mtimeMs})}}i.sort((d,h)=>h.mtime-d.mtime);const c=[];for(const d of i){const u=(await nn(d.filePath,"utf-8")).split(`
195
- `),p=jm(u);if(p.length===0)continue;const m=p.find(w=>w.type==="user_prompt"),f=d.stem;let y=(m==null?void 0:m.slug)||"",g=(m==null?void 0:m.timestamp)||"";g||(g=new Date(d.mtime).toISOString());let x;if(d.filePath.endsWith(".log")){d.stem.endsWith("-stale")?y=y||"rule-reflection/stale":d.stem.endsWith("-conversation")?y=y||"rule-reflection/conversation":d.stem.endsWith("-interruption")?y=y||"rule-reflection/interruption":y=y||"rule-reflection";const w=d.filePath.replace(/\.log$/,".context");if(rt(w))try{x=await nn(w,"utf-8")}catch{}}const v=p.filter(w=>w.type==="tool_call").length,b=p.filter(w=>w.type==="assistant_text").length;for(const w of p)w.type==="tool_call"&&w.name&&w.input&&(w.summary=km(w.name,w.input));if(a&&!(f.toLowerCase().includes(a)||y.toLowerCase().includes(a)||p.some(A=>Im(A,a))))continue;for(const w of p)w.type==="tool_result"&&w.content&&w.content.length>bs&&(w.truncated=!0,w.fullLength=w.content.length,w.content=w.content.slice(0,bs));const C=_m(p),N=Tm(p),k=Mm(x);c.push({id:f,slug:y,timestamp:g,stats:{toolCalls:v,textBlocks:b},entries:p,context:x,conversationSnippet:k,ruleChanges:C,hasConfusion:N})}return Response.json({agents:c})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const Rm=Object.freeze(Object.defineProperty({__proto__:null,loader:$m},Symbol.toStringTag,{value:"Module"}));async function Dm({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const a=ar(r);try{return await qt(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error clearing log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Lm({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=ar(t);try{if(!rt(r))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 nn(r,"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 s=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Fm=Object.freeze(Object.defineProperty({__proto__:null,action:Dm,loader:Lm},Symbol.toStringTag,{value:"Module"}));async function Om(e,t){var o,i,c,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Le();const r=await lt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(o=r.scenarios)==null?void 0:o.find(p=>p.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={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 ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=a.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function zm({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return B({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Om(r,a);return console.log("[API] Function execution completed successfully"),B({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),B({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ym=Object.freeze(Object.defineProperty({__proto__:null,action:zm},Symbol.toStringTag,{value:"Module"}));function Bm({request:e}){return B({status:"ok"})}async function Um({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await dt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("action"),o=a.get("analysisId"),i=a.get("scenarioId");if(!s||!o)return B({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return B({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await $e();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return B({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return B({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return B({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),B({error:"Failed to control interactive mode",details:s},{status:500})}}const Wm=Object.freeze(Object.defineProperty({__proto__:null,action:Um,loader:Bm},Symbol.toStringTag,{value:"Module"}));async function Hm({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:a}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),a&&a.length>0){const s=ge();if(s)for(const o of a){const i=ie.join(s,".codeyam","captures","screenshots",o);try{await fe.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 kc({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Vm=Object.freeze(Object.defineProperty({__proto__:null,action:Hm},Symbol.toStringTag,{value:"Module"})),an="/tmp/codeyam",Wr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Yo=500,Jm=Yo*1024*1024;function St(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function _n(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Bo(e){return St("config user.email",e)}function Gm(e){const t=Z.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function qm(e,t=20){const r=Z.join(an,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
196
- `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function Km(e){try{const t=await fetch(`${Wr}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function Qm(e,t){try{Me(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function Zm(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),h=Z.join(an,`delta-staging-${d}`),u=Z.join(h,"delta");K.mkdirSync(u,{recursive:!0});try{const p=St("diff --binary HEAD",t)||"";K.writeFileSync(Z.join(u,"tracked.patch"),p?p+`
197
- `:"");const m=St("ls-files --others --exclude-standard",t);if(m){const x=Z.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const v of m.split(`
198
- `).filter(Boolean)){const b=Z.join(t,v),C=Z.join(x,v);if(K.existsSync(b)){const N=Z.dirname(C);K.mkdirSync(N,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,C)}}}const f=Z.join(t,".codeyam");if(K.existsSync(f)){const x=Z.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(Z.join(u,"meta.json"),JSON.stringify(s,null,2));const y=Z.join(an,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,Z.join(u,"codeyam-log.txt")):K.writeFileSync(Z.join(u,"codeyam-log.txt"),`# Log file not found
199
- `);const g=Z.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,Z.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(K.writeFileSync(Z.join(u,"screenshot.jpg"),o),c(`Screenshot included (${_n(o.length)})`));try{Me(`tar -czf "${a}" -C "${h}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(h,{recursive:!0,force:!0})}}async function Xm(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=St("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=St("rev-parse --abbrev-ref HEAD",t)||"unknown",h=St("status --porcelain",t),u=St("remote get-url origin",t),p=h!==null&&h.length>0,m=Ao(r),f=Gm(t);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:r,git:{sha:c,branch:d,isDirty:p,remoteUrl:u},versions:{cli:m.cliVersion,webserver:m.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=Z.join(an,`base-${c}-${x}.tar.gz`),b=Z.join(an,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const C=await Km(c);let N=null;C?i("Server already has base, skipping..."):(i("Generating base archive..."),Qm(t,v),N=K.statSync(v).size,i(`Base archive: ${_n(N)}`)),i("Generating delta archive..."),Zm({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:s,onProgress:o});const w=K.statSync(b).size;i(`Delta archive: ${_n(w)}`);const A=(N||0)+w;if(A>Jm)throw K.existsSync(v)&&K.unlinkSync(v),K.unlinkSync(b),new Error(`Bundle too large: ${_n(A)} (max: ${Yo} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:C?null:v,deltaPath:b,metadata:g,baseSha:c,baseSize:N,deltaSize:w}}async function ep(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),h=K.statSync(r),u=t?K.statSync(t):null,p=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const m=await fetch(`${Wr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:p,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:s.timestamp,git:s.git,versions:s.versions,system:s.system,feedback:s.feedback}})});if(!m.ok){const C=await m.json();throw new Error(C.error||`Server returned ${m.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await m.json(),x=[];if(t&&g){d("Uploading base...");const C=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:C}).then(N=>{if(!N.ok)throw new Error(`Base upload failed: ${N.status}`)}))}d("Uploading delta...");const v=K.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(C=>{if(!C.ok)throw new Error(`Delta upload failed: ${C.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${Wr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const C=await b.json();throw new Error(C.error||`Confirm failed: ${b.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function tp({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),s=t.get("email"),o=t.get("source"),i=t.get("entitySha"),c=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("entityName"),p=t.get("entityType"),m=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=a||void 0;!g&&u&&(m?g=`Issue on ${u} scenario "${m}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const A=await y.arrayBuffer();x=Buffer.from(A),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=ge();if(!v)return B({error:"Project root not found"},{status:500});const b=await $e();if(!b)return B({error:"Project slug not found"},{status:500});const C={issueType:r||"other",description:g,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:qm(b,20),entityName:u||void 0,entityType:p||void 0,scenarioName:m||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${C.source}, issue: ${C.issueType}`);const N=await Xm({projectRoot:v,projectSlug:b,feedback:C,screenshot:x,onProgress:A=>{console.log(`[Bundle] ${A}`)}}),k=(N.baseSize||0)+N.deltaSize;console.log(`[Bundle] Archives created: delta=${N.deltaSize} bytes${N.basePath?`, base=${N.baseSize} bytes`:" (base reused)"}`);const w=await ep({basePath:N.basePath,deltaPath:N.deltaPath,projectSlug:b,metadata:N.metadata,baseSha:N.baseSha,deltaSize:N.deltaSize,onProgress:A=>{console.log(`[Bundle] ${A}`)}});return console.log(`[Bundle] Upload complete: ${w.bundleId}`),B({success:!0,reportId:w.bundleId,size:k})}catch(t){return console.error("[Bundle] Error:",t),B({error:t.message||"Failed to generate bundle"},{status:500})}}function np(){const e=ge(),t=e?Bo(e):null;return B({defaultEmail:t})}const rp=Object.freeze(Object.defineProperty({__proto__:null,action:tp,loader:np},Symbol.toStringTag,{value:"Module"}));function At(){const e=process.memoryUsage(),t=Tl.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(Fr.totalmem()/1024/1024),freeMemory:Math.round(Fr.freemem()/1024/1024)}}}function ap(){const e=At();console.log(`
200
- [Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function sp(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=At();global.gc();const t=At(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function op(){const e=At(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},a=[];return r.highHeapUsage&&a.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:a,hasIssues:a.length>0}}function ip({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const a=sp(),s=At();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:s})}case"detailed":{const a=ap();return Response.json({success:!0,stats:a})}case"leaks":{const a=op(),s=At();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=At();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 lp=Object.freeze(Object.defineProperty({__proto__:null,loader:ip},Symbol.toStringTag,{value:"Module"})),Nn=Zr(Qr);async function cp({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const a=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const s=await Promise.all(a.map(async o=>{const i=dp(o),c=i?await up(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:s})}function dp(e){try{return process.kill(e,0),!0}catch{return!1}}async function up(e){if(process.platform==="win32")try{const{stdout:r}=await Nn(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),a=r.match(/"([^"]+)"/);if(!a)return null;const s=a[1];if(s.toLowerCase()==="node.exe")try{const{stdout:o}=await Nn(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return s}catch{return null}try{const{stdout:r}=await Nn(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:a}=await Nn(`ps -p ${e} -o args=`),s=a.trim(),o=s.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:s.split(" ")[0]||null}catch{return null}}}const hp=Object.freeze(Object.defineProperty({__proto__:null,loader:cp},Symbol.toStringTag,{value:"Module"})),mp=Qn(import.meta.url),pp=Z.dirname(mp);function fp({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Po(),r=ge()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const a=(t==null?void 0:t.port)||3111,s=Z.join(pp,"..","..","..","..","webserver","bootstrap.js"),o=Z.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(Z.join(o,"background-server.log"),"a"),c=K.openSync(Z.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(Z.join(o,"background-server.log"),`
201
- [${d}] Server restart requested via dashboard
202
- `),Rd();const h=Kn("node",[s],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const gp=Object.freeze(Object.defineProperty({__proto__:null,action:fp},Symbol.toStringTag,{value:"Module"}));async function yp({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((c,d)=>{var p,m,f,y,g;const h=(m=(p=c.metadata)==null?void 0:p.data)==null?void 0:m.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[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(h)?h.length:"not-array",argumentsDataPreview:u})});const s=a.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await Wc(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((c,d)=>{var u,p;const h=(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(h)?h.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const xp=Object.freeze(Object.defineProperty({__proto__:null,action:yp},Symbol.toStringTag,{value:"Module"})),bp=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function vp({request:e}){try{const r=new URL(e.url).searchParams.get("search")||"",a=new URL(`/api/agent-transcripts${r?`?search=${encodeURIComponent(r)}`:""}`,e.url),o=await(await fetch(a.toString())).json();return o.error?B({agents:[],error:o.error,search:r}):B({agents:o.agents||[],error:null,search:r})}catch(t){return console.error("Failed to load agent transcripts:",t),B({agents:[],error:"Failed to load agent transcripts",search:""})}}function wp(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function Cp(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function Mn({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},a={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:a[e]||e})}function Np({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let a=typeof r=="string"?r:JSON.stringify(r);return a.length>500&&(a=a.slice(0,500)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:a})]},t)})})}function Sp({content:e,truncated:t,fullLength:r}){const[a,s]=P(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!a&&"..."]}),t&&n("button",{onClick:()=>s(!a),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:a?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Ep({entry:e,pairedResult:t}){const[r,a]=P(!1),s=wp(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Mn,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Mn,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>a(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(st,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(jt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Mn,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:s})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Np,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Sp,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Ap({context:e}){const[t,r]=P(!1);return l("div",{className:"my-2",children:[l("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(st,{className:"w-3 h-3 text-gray-400"}):n(jt,{className:"w-3 h-3 text-gray-400"}),n(Mn,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function kp({snippet:e}){const[t,r]=P(!1),a=e.split(`
203
- `).filter(c=>c.trim()),s=a.slice(0,4),o=a.length>4,i=t?a:s;return l("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n(qi,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),l("span",{className:"text-[10px] text-blue-500",children:[a.length," message",a.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((c,d)=>{const h=c.match(/^\[(\w+)\]:\s*(.*)/);if(!h)return null;const[,u,p]=h,m=u==="user";return l("div",{className:"text-xs",children:[l("span",{className:`font-bold ${m?"text-blue-700":"text-gray-500"}`,children:[m?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:p.length>200?p.slice(0,200)+"...":p})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${a.length} messages`})]})}function Pp({change:e}){const[t,r]=P(!1),a=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>a&&r(!t),className:`text-left w-full ${a?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[a&&(t?n(st,{className:"w-3 h-3 inline flex-shrink-0"}):n(jt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function _p({changes:e}){const t=e.filter(a=>a.action==="touched"),r=e.filter(a=>a.action!=="touched");return l("div",{className:"my-2 bg-green-50 border border-green-200 rounded-md p-3",children:[n("div",{className:"text-xs font-bold text-green-800 mb-1",children:"Rule Changes:"}),l("ul",{className:"text-xs text-green-700 space-y-0.5 font-mono",children:[r.map((a,s)=>n(Pp,{change:a},s)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Mp({agent:e,defaultOpen:t,isAdmin:r}){const[a,s]=P(t),[o,i]=P(!1),[c,d]=P(null),h=re(()=>{const v={};for(const b of e.entries)b.type==="tool_result"&&b.tool_use_id&&(v[b.tool_use_id]=b);return v},[e.entries]),u=re(()=>{const v=new Set;for(const b of e.entries)b.type==="tool_call"&&b.tool_use_id&&h[b.tool_use_id]&&v.add(b.tool_use_id);return v},[e.entries,h]),p=v=>{v.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(b=>b.json()).then(b=>{b.success?d(`Saved to ${b.fixturePath}`):d(`Error: ${b.error}`)}).catch(b=>{d(`Error: ${b instanceof Error?b.message:String(b)}`)}).finally(()=>{i(!1)})},m=(e.ruleChanges||[]).filter(v=>v.action!=="touched"),f=(e.ruleChanges||[]).filter(v=>v.action==="touched"),y=m.length>0,g=f.length>0,x=y||g;return l("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${y?"border-green-300":"border-gray-200"}`,children:[l("button",{onClick:()=>s(!a),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[a?n(st,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(jt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),y&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Gr,{className:"w-3 h-3"}),m.length===1?"1 rule changed":`${m.length} rules changed`]}),!y&&g&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[f.length," timestamp",f.length!==1?"s":""," ","touched"]}),e.hasConfusion&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(Tn,{className:"w-3 h-3"}),"Confusion Detected"]}),l("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks"]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[Cp(e.timestamp),r&&y&&l("button",{onClick:p,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(Gi,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),c&&n("div",{className:`px-4 py-2 text-xs font-mono ${c.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:c}),a&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.conversationSnippet&&n(kp,{snippet:e.conversationSnippet}),x&&n(_p,{changes:e.ruleChanges}),e.context&&n(Ap,{context:e.context}),e.entries.map((v,b)=>{if(v.type==="tool_result"&&v.tool_use_id&&u.has(v.tool_use_id))return null;const C=v.type==="tool_call"&&v.tool_use_id?h[v.tool_use_id]:void 0;return n(Ep,{entry:v,pairedResult:C},`${e.id}-${b}`)})]})]})}const Tp=De(function(){const{agents:t,error:r,search:a}=Be(),s=Tt(),o=Mi("root"),i=(o==null?void 0:o.isAdmin)??!1,[c,d]=P(a),[h,u]=P(!1),[p,m]=P(0);Xe({source:"agent-transcripts-page"});const f=g=>{g.preventDefault(),window.location.href=`/agent-transcripts${c?`?search=${encodeURIComponent(c)}`:""}`},y=()=>{u(!h),m(g=>g+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{s("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Ji,{className:"w-5 h-5"})}),n(jn,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:f,className:"relative flex-1 max-w-md",children:[n(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:c,onChange:g=>d(g.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:y,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:[t.length," agent",t.length!==1?"s":""," found",a&&l("span",{children:[" ","matching “",a,"”",n(se,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(jn,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(g=>n(Mp,{agent:g,defaultOpen:h,isAdmin:i},g.id))},p)]})})}),jp=Object.freeze(Object.defineProperty({__proto__:null,default:Tp,loader:vp,meta:bp},Symbol.toStringTag,{value:"Module"}));async function Ip({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:s}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!vs(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),h=vs(r);if(h){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(s)try{await mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function vs(e){try{return process.kill(e,0),!0}catch{return!1}}const $p=Object.freeze(Object.defineProperty({__proto__:null,action:Ip},Symbol.toStringTag,{value:"Module"})),Rp=Qn(import.meta.url),Dp=ie.dirname(Rp),ws="/tmp/claude-rule-markers",Lp=ie.resolve(Dp,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function Fp(e){const t=[],r=new Set;for(const a of e.split(`
204
- `)){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const h=String(d.name||""),u=d.input||{};if(h==="Write"||h==="Edit"){const p=String(u.file_path||"");if(p.includes(".claude/rules/")){const m=p.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${h}:${m}`;r.has(f)||(r.add(f),t.push({action:h==="Write"?"created":"modified",filePath:m}))}}else if(h==="Bash"){const p=String(u.command||"");if(p.includes("codeyam memory touch")){const m=`touch:${p}`;r.has(m)||(r.add(m),t.push({action:"touched",filePath:p}))}}}}return t}async function Op({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const a=ie.join(ws,`${r}.log`);if(!rt(a))return Response.json({error:`Log file not found: ${a}`},{status:404});const s=await nn(a,"utf-8"),o=ie.join(ws,`${r}.context`);let i=null;if(rt(o))try{i=await nn(o,"utf-8")}catch{}const c=Fp(s),h=i?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(y=>i.toLowerCase().includes(y)):!1,u=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",p=r.slice(0,8)+u,m=ie.join(Lp,p);await yl(m,{recursive:!0}),await qt(ie.join(m,"agent-log.jsonl"),s),i&&await qt(ie.join(m,"context.md"),i),await qt(ie.join(m,"rule-changes.json"),JSON.stringify(c,null,2)),await qt(ie.join(m,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:c.length},null,2));const f=ie.relative(process.cwd(),m);return console.log(`[api.save-fixture] Saved fixture to ${f}`),Response.json({success:!0,fixturePath:f})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const zp=Object.freeze(Object.defineProperty({__proto__:null,action:Op},Symbol.toStringTag,{value:"Module"}));async function Yp({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=ge();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=ie.join(r,".codeyam","captures","screenshots",t);try{await fe.access(a);const s=await fe.readFile(a),o=ie.extname(a).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(s,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Bp=Object.freeze(Object.defineProperty({__proto__:null,loader:Yp},Symbol.toStringTag,{value:"Module"})),Cs={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 ma({type:e,className:t=""}){const r=Cs[e]||Cs.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const Up={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 Sn({variant:e,pid:t,label:r,className:a=""}){const s=Up[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${a}`,style:{backgroundColor:s.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:s.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:s.textColor},children:o})})}function Ye({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=P("loading"),[c,d]=P(!1),h=Ne(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,p=()=>{i("success"),d(!0)},m=()=>{i("error"),d(!1)};return ee(()=>{i("loading"),d(!1);const f=h.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:s,children:[n("img",{ref:h,src:u,alt:r,onLoad:p,onError:m,className:a||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&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:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let Ns=!1;function Wp(){if(Ns)return;const e=document.createElement("style");e.textContent=`
205
- @keyframes strongPulse {
206
- 0%, 100% { opacity: 0.2; }
207
- 50% { opacity: 1; }
208
- }
209
- `,document.head.appendChild(e),Ns=!0}function pa({size:e="medium",className:t=""}){typeof document<"u"&&Wp();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:s,gap:o}=r[e];return l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Hp=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function Vp({request:e,context:t,params:r}){var Y,z,$,E,W,H,V,ae;let a=t.analysisQueue;a||(a=await dt());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!a)return B({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),h=await $e();let u=null;if(h&&((Y=d==null?void 0:d.currentlyExecuting)!=null&&Y.commitSha)){const{project:O,branch:j}=await Ie(h),R=await Ln({projectId:O.id,branchId:j.id,shas:[d.currentlyExecuting.commitSha]});u=R&&R.length>0?R[0]:null}else u=await Ot();const p=async O=>{const j=await Lt(O);if(!j)return null;const{getAnalysesForEntity:R}=await Promise.resolve().then(()=>od),G=await R(O,!1);return{...j,analyses:G||[]}},m=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async O=>{const j=[];if(O.entityShas&&O.entityShas.length>0){const R=O.entityShas.map(te=>p(te)),G=await Promise.all(R);j.push(...G.filter(te=>te!==null))}return{...O,entities:j}}));let f=null;if(d!=null&&d.currentlyExecuting){const O=d.currentlyExecuting,j=[];if(O.entityShas&&O.entityShas.length>0){const R=O.entityShas.map(te=>p(te)),G=await Promise.all(R);j.push(...G.filter(te=>te!==null))}f={...O,entities:j}}const y=f?m.filter(O=>O.id!==f.id):m,g=(($=(z=u==null?void 0:u.metadata)==null?void 0:z.currentRun)==null?void 0:$.currentEntityShas)||[],v=(await Promise.all(g.map(O=>p(O)))).filter(O=>O!==null),b=[];if(h)try{const{project:O,branch:j}=await Ie(h),R=await Ln({projectId:O.id,branchId:j.id,limit:100});for(const G of R){const te=((E=G.metadata)==null?void 0:E.historicalRuns)||[];b.push(...te)}}catch(O){console.error("[activity.tsx] Failed to load historical runs from commits:",O)}const C=[...b].sort((O,j)=>{const R=O.lastCaptureAt||O.analysisCompletedAt||O.archivedAt||O.createdAt||"";return(j.lastCaptureAt||j.analysisCompletedAt||j.archivedAt||j.createdAt||"").localeCompare(R)}),N=(o-1)*i,k=N+i,w=C.slice(N,k),A=Math.ceil(C.length/i),M=await Promise.all(w.map(async O=>{const j=O.currentEntityShas||[];if(j.length===0)return{...O,entities:[]};const R=await Promise.all(j.map(G=>p(G)));return{...O,entities:R.filter(G=>G!==null)}})),I=!!f,D=y.length,L=C.filter(O=>{const j=!!O.failedAt,R=O.readyToBeCaptured,G=O.capturesCompleted??0,te=R===void 0?!0:R===0||G>=R;return!j&&!!O.analysisCompletedAt&&te}),_=new Set(((W=f==null?void 0:f.entities)==null?void 0:W.map(O=>O.sha))||[]),S=L.filter(O=>!(O.currentEntityShas||[]).some(R=>_.has(R))),F=(await Promise.all(S.slice(0,3).map(async O=>{const j=O.currentEntityShas||[];if(j.length===0)return{run:O,entities:[]};const R=await Promise.all(j.map(G=>p(G)));return{run:O,entities:R.filter(G=>G!==null)}}))).flatMap(({run:O,entities:j})=>j.map(R=>({...R,runId:O.id,completedAt:O.lastCaptureAt||O.analysisCompletedAt||O.archivedAt||O.createdAt})));let q=[],J=null,U=null;if((V=(H=u==null?void 0:u.metadata)==null?void 0:H.currentRun)!=null&&V.analysisCompletedAt&&v.length>0){const O=v[0].sha;J=v[0];const j=await tr(O);j&&j.length>0&&j[0].scenarios&&(q=j[0].scenarios,U=j[0].status)}return B({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(ae=u==null?void 0:u.metadata)==null?void 0:ae.currentRun,historicalRuns:M,totalHistoricalRuns:C.length,currentPage:o,totalPages:A,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:c,hasCurrentActivity:I,queuedCount:D,recentCompletedEntities:F,hasMoreCompletedRuns:S.length>3,currentEntityScenarios:q,currentEntityForScenarios:J,currentAnalysisStatus:U})}function Jp({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:s.map(o=>{const i=e===o.id;return n(se,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
210
- relative pb-4 px-2 text-sm transition-colors cursor-pointer
211
- ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
212
- `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
213
- inline-block w-2 h-2 rounded-full
214
- ${i?"":"bg-gray-400"}
215
- `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Gp({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var T,F,q,J;const[p,m]=P({}),[f,y]=P({isKilling:!1,current:0,total:0}),g=ot(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),C=b&&!!(t!=null&&t.capturePid),N=!b,k=x,w=d||[],{lastLine:A}=gt(a,k);ee(()=>{if(!t)return;const U=[t.analyzerPid,t.capturePid].filter(E=>!!E);if(U.length===0)return;let Y=!0;const z=async()=>{try{const W=await(await fetch(`/api/process-status?pids=${U.join(",")}`)).json();if(W.processes&&Y){const H={};W.processes.forEach(V=>{H[V.pid]={isRunning:V.isRunning,processName:V.processName}}),m(H)}}catch(E){Y&&console.error("Failed to fetch process statuses:",E)}};z();const $=setInterval(()=>void z(),5e3);return()=>{Y=!1,clearInterval($)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[M,I]=P(!1),[D,L]=P(!1);ee(()=>{v.length<=3&&M&&I(!1)},[v.length,M]),ee(()=>{i.length<=3&&D&&L(!1)},[i.length,D]);const _=M?v:v.slice(0,3),S=v.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[k?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:[n(Ze,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:C?"Capturing...":"Analyzing..."})]}),_.map(U=>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:[n("div",{children:n(Ve,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:U.name}),U.entityType&&n(ma,{type:U.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:U.filePath,children:U.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},U.sha)),S&&!M&&l("button",{onClick:()=>I(!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:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),M&&S&&n("button",{onClick:()=>I(!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"}),C&&w&&w.length>0&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:w.map(U=>{var V,ae,O,j;if(!U.id)return null;const Y=(ae=(V=U.metadata)==null?void 0:V.screenshotPaths)==null?void 0:ae[0],z=(O=U.metadata)==null?void 0:O.noScreenshotSaved,$=Y&&!z,E=(j=u==null?void 0:u.scenarios)==null?void 0:j.find(R=>R.name===U.name),H=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt||!$&&!z;return n(se,{to:`/entity/${h.sha}/scenarios/${U.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:H?"#f9f9f9":void 0,borderColor:H?"#efefef":"#ccc"},children:$?n(Ye,{screenshotPath:Y,alt:U.name,className:"w-full h-full object-contain bg-gray-100"}):H?n("div",{className:"w-full h-full flex items-center justify-center",children:n(pa,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},U.id)})}),A&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.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:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Sn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(N||((T=p[t.analyzerPid])==null?void 0:T.isRunning))&&n(Sn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Sn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(C||((F=p[t.capturePid])==null?void 0:F.isRunning))&&n(Sn,{variant:"running"})]}),(((q=p[t==null?void 0:t.analyzerPid])==null?void 0:q.isRunning)||((J=p[t==null?void 0:t.capturePid])==null?void 0:J.isRunning))&&n("button",{onClick:()=>{const U=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter($=>{var E;return!!$&&((E=p[$])==null?void 0:E.isRunning)});if(U.length===0)return;const Y=U.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${Y})?`))return;y({isKilling:!0,current:1,total:U.length}),(async()=>{for(let $=0;$<U.length;$++){const E=U[$];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:E,commitSha:s||""})})}catch(W){console.error(`Failed to kill process ${E}:`,W)}$<U.length-1&&y({isKilling:!0,current:$+2,total:U.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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Ys,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("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"," ",n(se,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(se,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(D?i:i.slice(0,3)).map(U=>{var $;const Y=($=U.analyses)==null?void 0:$[0],z=(Y==null?void 0:Y.scenarios)||[];return Y==null||Y.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Ve,{type:U.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:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",title:U.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:U.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:U.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:U.filePath,children:U.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:E=>{E.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:E=>{E.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),z.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:z.map(E=>{var ae,O,j;if(!E.id)return null;const W=(O=(ae=E.metadata)==null?void 0:ae.screenshotPaths)==null?void 0:O[0],H=(j=E.metadata)==null?void 0:j.noScreenshotSaved,V=W&&!H;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(se,{to:`/entity/${U.sha}/scenarios/${E.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:V?"#f3f4f6":"#FAFAFA",borderColor:V?"#d1d5db":"#BCCDD3",borderStyle:V?"solid":"dashed"},onMouseEnter:R=>{V&&(R.currentTarget.style.borderColor="#005C75",R.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:R=>{R.currentTarget.style.borderColor=V?"#d1d5db":"#BCCDD3",R.currentTarget.style.boxShadow="none"},children:V?n(Ye,{screenshotPath:W,alt:E.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E.name})]},E.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},U.sha)}),i.length>3&&!D&&l("button",{onClick:()=>L(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),D&&i.length>3&&n("button",{onClick:()=>L(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function qp({queueJobs:e,state:t,currentRun:r}){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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Ki,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[a,s]=P(null),[o,i]=P(null),[c,d]=P(null),[h,u]=P(!1),[p,m]=P(!1),[f,y]=P(new Set),g=ot();ee(()=>{e.length<=3&&p&&m(!1)},[e.length,p]);const x=w=>{s(w)},v=(w,A)=>{w.preventDefault(),i(A)},b=async(w,A)=>{if(w.preventDefault(),!a){i(null);return}const M=e.findIndex(L=>L.id===a);if(M===-1){s(null),i(null);return}if(M===A){s(null),i(null);return}const I=M<A?"down":"up",D=Math.abs(A-M);u(!0);try{for(let L=0;L<D;L++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:I})});g.revalidate()}catch(L){console.error("Failed to reorder job:",L)}finally{u(!1),s(null),i(null)}},C=()=>{h||(s(null),i(null))},N=async w=>{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:w})}),window.location.reload()}catch(A){console.error("Failed to cancel job:",A)}},k=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(w){console.error("Failed to cancel jobs:",w)}};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&&n("button",{onClick:()=>void k(),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(w=>{var S,T,F,q;const A=e.findIndex(J=>J.id===w.id),M=c===A,I=a===w.id,D=o===A,L=f.has(w.id),_=((S=w.entities)==null?void 0:S.length)>0?L?w.entities:w.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:I||h?.5:1,transform:D&&a!==null&&!I?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":I?"grabbing":"grab"},onMouseEnter:()=>d(A),onMouseLeave:()=>d(null),draggable:!h,onDragStart:J=>{x(w.id),J.dataTransfer.effectAllowed="move"},onDragOver:J=>v(J,A),onDrop:J=>void b(J,A),onDragEnd:C,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Qi,{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:[_.length>0?l(he,{children:[_.map(J=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Ve,{type:J.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${J.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:J.name}),J.entityType&&n(ma,{type:J.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:J.filePath})]})]})})},J.sha)),((T=w.entities)==null?void 0:T.length)>3&&n("button",{onClick:()=>{y(J=>{const U=new Set(J);return U.has(w.id)?U.delete(w.id):U.add(w.id),U})},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:L?"Show less":`+${w.entities.length-3} more ${w.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(In,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((F=w.entityNames)==null?void 0:F[0])||(w.type==="analysis"?"Analysis Job":w.type==="recapture"?"Recapture Job":w.type==="debug-setup"?"Debug Setup":w.type.charAt(0).toUpperCase()+w.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((q=w.filePaths)==null?void 0:q[0])||(w.filePaths&&w.filePaths.length>1?`${w.filePaths.length} files`:w.entityShas&&w.entityShas.length>0?`${w.entityShas.length} ${w.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[M&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Zi,{size:20})}),n("button",{onClick:()=>void N(w.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"})]})]})]},w.id)}),e.length>3&&!p&&l("button",{onClick:()=>m(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),p&&e.length>3&&n("button",{onClick:()=>m(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function Kp({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){if(t===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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Xi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=P(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(p=>{d.push({...p,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var y;const p=(y=u.analyses)==null?void 0:y[0],m=(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:[n("div",{children:n(Ve,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),m.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[m.slice(0,8).map(g=>{var C,N,k;if(!g.id)return null;const x=(N=(C=g.metadata)==null?void 0:C.screenshotPaths)==null?void 0:N[0],v=(k=g.metadata)==null?void 0:k.noScreenshotSaved,b=x&&!v;return n(se,{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?n(Ye,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),m.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",m.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&&n("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 Qp=De(function(){const t=Be(),r=Fs(),[a,s]=P(!1);Xe({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(Jp,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(Gp,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(qp,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(Kp,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n(pt,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),Zp=Object.freeze(Object.defineProperty({__proto__:null,default:Qp,loader:Vp,meta:Hp},Symbol.toStringTag,{value:"Module"}));async function Uo(e,t,r){var N,k;await Le();const a=await lt({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 s=ge();if(!s)throw new Error("Project root not found");const o=Z.join(s,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=ar(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Ie(c),u=((N=h.metadata)==null?void 0:N.packageManager)||"npm",p=3112,m=ct(c),f=((k=h.metadata)==null?void 0:k.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=Ec({filePath:a.filePath,webapps:f,environmentVariables:y,port:p,packageManager:u});await Ft(e,w=>{if(w&&(w.readyToBeCaptured=!0,w.scenarios))for(const A of w.scenarios)(!t||A.name===t)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:c,analysisId:e,scenarioId:t,prepOnly:!0}),v=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:m}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${m}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:m,projectSlug:c,port:p,packageManager:u,framework:g.framework,instructions:b}}async function Xp({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),s=r.searchParams.get("scenarioId")||void 0;if(!a)return B({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await dt()),!o)return B({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Uo(a,s,o);return B({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),B({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ef({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await dt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return B({error:"Missing required field: analysisId"},{status:400});const i=await Uo(s,o,r);return B({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),B({error:"Failed to setup debug environment",details:s},{status:500})}}const tf=Object.freeze(Object.defineProperty({__proto__:null,action:ef,loader:Xp},Symbol.toStringTag,{value:"Module"})),nf=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Wo(e){const t=wl("sha256",nf);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function rf(e,t){return t===Wo(e)}async function af({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return B({success:!1,error:"Unlock code is required"},{status:400});const a=await $e();return a?rf(a,r)?(await On({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),B({success:!0})):B({success:!1,error:"Invalid unlock code"},{status:400}):B({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),B({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const sf=Object.freeze(Object.defineProperty({__proto__:null,action:af},Symbol.toStringTag,{value:"Module"}));async function of({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await dt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return B({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return B({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const c=await vm(s,i,r);return console.log("[API] Recapture queued",c),B({success:!0,message:"Recapture queued",...c})}catch(a){return console.log("[API] Error during recapture:",a),B({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const lf=Object.freeze(Object.defineProperty({__proto__:null,action:of},Symbol.toStringTag,{value:"Module"}));function cf(e,t){var i,c,d,h,u;const r=((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(!r){const p=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return p||m?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 s=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||s){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 df(e){return cf(e).hasOutdatedSimulations}function dr(e,t,r,a,s){var J,U,Y,z,$,E,W,H;const o=(J=t==null?void 0:t.scenarios)==null?void 0:J.find(V=>V.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,p=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,m=!!((Y=(U=e.metadata)==null?void 0:U.screenshotPaths)!=null&&Y[0])||!!((z=e.metadata)!=null&&z.executionResult),f=c&&!d,y=o==null?void 0:o.error,g=(E=($=e.metadata)==null?void 0:$.executionResult)==null?void 0:E.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const V of t.errors)x.push({source:`${V.phase} phase`,message:V.message});if(t!=null&&t.steps)for(const V of t.steps)V.error&&x.push({source:V.name,message:V.error});const v=!m&&!y&&!g&&x.length>0,b=!!(y||g||p||v),C=p?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(v?`Analysis error: ${x[0].message}`:null),N=p?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,w=(a&&s?s.jobs.some(V=>{var ae;return((ae=V.entityShas)==null?void 0:ae.includes(a))||V.type==="analysis"&&V.entityShas&&V.entityShas.length===0})||((H=(W=s.currentlyExecuting)==null?void 0:W.entityShas)==null?void 0:H.includes(a)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,A=i&&!c&&!h&&!b,M=(w||A||f)&&!b,I=(w||A)&&r===!1&&!m;let D;I?D="crashed":b?D="error":m||h?D="completed":f?D="capturing":A?D="starting":w?D="queued":D="pending";let L="📷",_="pending",S=!1,T=`Not captured: ${e.name}`;const F="border-gray-300",q=b||I?"bg-red-50":"bg-white";return b||I?(L="⚠️",_="error",T=`Error: ${I?"Analysis process crashed":C||"Unknown error"}`):w?(L="⋯",_="queued",T=`Queued: ${e.name}`):A?(L="⋯",_="starting",S=!0,T=`Starting server for ${e.name}...`):f&&!b?(L="⋯",_="capturing",S=!0,T=`Capturing ${e.name}...`):m&&(L="✓",_="completed",T=e.name),{hasError:b||I,errorMessage:I?"Analysis process crashed":C,errorStack:I?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:m,hasCrashed:I,isAnalyzing:M,isQueued:w,isServerStarting:A,status:D,icon:L,iconType:_,shouldSpin:S,title:T,borderColor:F,bgColor:q}}function Ho({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var N,k,w,A,M,I;const o=dr(e,void 0,void 0,t,void 0),i=(N=e.metadata)==null?void 0:N.executionResult,c=!!i,h=(((w=(k=e.metadata)==null?void 0:k.data)==null?void 0:w.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,p=((M=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:M.length)||0,m=((I=i==null?void 0:i.timing)==null?void 0:I.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,p>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?s?{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"},v=a?`border-2 ${x.border}`:"",b=Array.from({length:3},(D,L)=>n("div",{className:`w-1 h-1 rounded-full ${L<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},L)),C=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
216
- ${h} args → ${u?"value":"void"}${p>0?` (${p} logs)`:""}
217
- ${m}ms`:`Not executed: ${e.name}`;return l(se,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:C,onClick:D=>D.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!o.hasError&&m>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:m>1e3?`${Math.round(m/1e3)}s`:`${m}ms`}),c&&!o.hasError&&p>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",p]})]})}function Hr({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Ss({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var g,x;if(t.entityType==="library")return n(Ho,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=dr(e,r,s,t.sha,a),p=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},m=`relative ${p.containerClass} ${c}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(se,{to:f(),className:`${m} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ye,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(pa,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Hr,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(el,{...v});default:return b}};return n(se,{to:f(),className:`${m} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:p.iconSize,children:y()})})}const $t=70;function uf({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:s,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:p,areScenariosStale:m,viewMode:f,setViewMode:y,isBreakdownView:g}){var S,T,F,q,J,U;const x=Ne(null),[v,b]=P(new Set),[C,N]=P(!1);ee(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const k=Y=>`/entity/${s}/scenarios/${Y}`,w=Y=>{b(z=>{const $=new Set(z);return $.has(Y)?$.delete(Y):$.add(Y),$})},A=(Y,z=2)=>{const E=Y.split(`
218
- `).slice(0,z).join(" ").trim();return E.length>$t?E.substring(0,$t-3):(Y.split(`
219
- `).length>z||Y.length>E.length,E)},M=re(()=>{var z;if(!((z=r==null?void 0:r.metadata)!=null&&z.executionFlows)||!(r!=null&&r.scenarios))return null;const Y=r.scenarios.filter($=>{var E;return!((E=$.metadata)!=null&&E.sameAsDefault)});return da(r.metadata.executionFlows,Y)},[r]),I=(M==null?void 0:M.totalFlows)||0,D=(M==null?void 0:M.coveredFlows)||0,L=(M==null?void 0:M.coveragePercentage)||0;(S=d==null?void 0:d.metadata)!=null&&S.defaultWidth||(T=r==null?void 0:r.metadata)!=null&&T.defaultWidth;const _=(F=r==null?void 0:r.status)!=null&&F.finishedAt?new Date(r.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:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${s}/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(L),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${s}/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,"/",I]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((U=e[0])==null?void 0:U.id)}`:`/entity/${s}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(se,{to:`/entity/${s}/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"]}),_&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:_})]}),p&&(m||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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((Y,z)=>{const $=!g&&(a==null?void 0:a.id)===Y.id,E=v.has(Y.id||"");return Y.id?l(se,{to:k(Y.id),ref:$?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${$?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Ss,{scenario:Y,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${E?"":"line-clamp-1"}`,children:Y.name}),Y.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[E?Y.description:A(Y.description),!E&&Y.description.length>$t&&l(he,{children:["...",n("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),w(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),E&&Y.description.length>$t&&n("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),w(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},z):null})})}),t.length>0&&!(p&&m)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>N(!C),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${C?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),C&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((Y,z)=>{const $=!g&&(a==null?void 0:a.id)===Y.id,E=v.has(Y.id||"");return Y.id?l(se,{to:`/entity/${s}/scenarios/${Y.id}`,ref:$?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${$?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Ss,{scenario:Y,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${E?"":"line-clamp-1"}`,children:Y.name}),Y.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[E?Y.description:A(Y.description),!E&&Y.description.length>$t&&l(he,{children:["...",n("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),w(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),E&&Y.description.length>$t&&n("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),w(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},z):null})})]})]})]})}function hf({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:p=!1,deleteError:m=null}){const[f,y]=P(""),g=async()=>{await r(f)},x=async v=>{await a(f,v),v||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:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(se,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>y(v.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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:s,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(se,{to:`/entity/${t}`,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:[n("button",{onClick:()=>void x(!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"}),n("button",{onClick:()=>void x(!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"}),o&&l(he,{children:[h?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:[n("button",{onClick:()=>void o(),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"}),n("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"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),m&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:m})]})]})]})}function mf({scenario:e,analysis:t,entity:r}){var i,c,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=h=>{var y,g,x;if(!h)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=h.sideEffects)==null?void 0:y.consoleOutput)||[];p.length>0&&(u.push(`Console Output: ${p.length} log ${p.length===1?"entry":"entries"} captured`),p.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const m=((g=h.sideEffects)==null?void 0:g.fileWrites)||[];m.length>0&&(u.push(`
220
- File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=h.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
221
- API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),h.error&&u.push(`
222
- Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
223
- `)};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:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?n("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"}):n("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:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const Nt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function En({scenarioId:e,analysisId:t}){const[r,a]=P(!1),[s,o]=P(!1),[i,c]=P(null),[d,h]=P(!1),u=e||t;if(!u)return null;const p=`/codeyam-diagnose ${u}`,m=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),a(!0)}catch(y){console.error("Screenshot capture failed:",y),a(!0)}finally{o(!1)}},f=()=>{a(!1),c(null)};return l(he,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Nt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:Nt.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:Nt.commandBoxBg,borderColor:Nt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:Nt.commandBoxText},children:p}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(p),h(!0),setTimeout(()=>h(!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":Nt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(kt,{size:14}):n(Rt,{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,"," ",n("button",{onClick:()=>void m(),disabled:s,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:Nt.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(Ks,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Es=1440,An=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],nt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Vo({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var G,te,ce,pe,me,be,Ce,Ee,Se,Pe,Te;const p=Ae(),[m,f]=P(!1),[y,g]=P(!1),[x,v]=P({name:"Desktop",width:Es,height:900}),[b,C]=P(Es),[N,k]=P(1),{customSizes:w,addCustomSize:A,removeCustomSize:M}=To(c),I=re(()=>[...An,...w],[w]),D=(ve,Q)=>{C(ve);const ue=I.find(ye=>ye.width===ve&&ye.height===Q);v({name:(ue==null?void 0:ue.name)||"Custom",width:ve,height:Q})},L=ve=>{C(ve.width),v({name:ve.name,width:ve.width,height:ve.height})},_=ve=>{A(ve,x.width,x.height??900),g(!1),v(Q=>({...Q,name:ve}))},S=(ve,Q)=>{C(ve);const ue=I.find(ye=>ye.width===ve&&ye.height===Q);v(ye=>({name:(ue==null?void 0:ue.name)||"Custom",width:ve,height:ye.height}))},T=(te=(G=e==null?void 0:e.metadata)==null?void 0:G.screenshotPaths)==null?void 0:te[0],F=re(()=>e?dr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),q=re(()=>{var Q,ue;const ve=[];if((Q=t==null?void 0:t.status)!=null&&Q.errors&&t.status.errors.length>0)for(const ye of t.status.errors)ve.push({source:`${ye.phase} phase`,message:ye.message,stack:ye.stack});if((ue=t==null?void 0:t.status)!=null&&ue.steps)for(const ye of t.status.steps)ye.error&&ve.push({source:ye.name,message:ye.error,stack:ye.errorStack});return ve},[(ce=t==null?void 0:t.status)==null?void 0:ce.errors,(pe=t==null?void 0:t.status)==null?void 0:pe.steps]),J=(F==null?void 0:F.errorMessage)||null,U=(F==null?void 0:F.errorStack)||null,{interactiveServerUrl:Y,isStarting:z,isLoading:$,showIframe:E,iframeKey:W,onIframeLoad:H}=mn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:a==="interactive"}),V=re(()=>Y||null,[Y]),ae=!i&&o&&e&&!((be=(me=e.metadata)==null?void 0:me.screenshotPaths)!=null&&be[0])&&((Ee=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:Ee.some(ve=>ve.name===e.name&&ve.screenshotStartedAt&&!ve.screenshotFinishedAt)),{lastLine:O}=gt(c,i||a==="interactive"||ae||!1);if(!e){if(i&&r)return l(he,{children:[n("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:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:ae?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),O&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:O}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),m&&c&&n(pt,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(q.length>0){const ve=q.length===1?((Se=q[0])==null?void 0:Se.message)||"An error occurred during analysis.":`${q.length} errors occurred during analysis.`;return l(he,{children:[n("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:[n("div",{className:"p-4 rounded",style:{backgroundColor:nt.background,border:`2px solid ${nt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(Hr,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:nt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ve," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:nt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(En,{analysisId:t==null?void 0:t.id})})]})}),m&&c&&n(pt,{projectSlug:c,onClose:()=>f(!1)})]})}return n("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:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{p.submit({entitySha:r.sha,filePath:r.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 n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(he,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
224
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
225
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
226
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
227
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
228
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||ae&&!T)&&!J&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:ae?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:ae?`Taking screenshots for ${((Pe=t==null?void 0:t.scenarios)==null?void 0:Pe.length)||0} scenario${((Te=t==null?void 0:t.scenarios)==null?void 0:Te.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),O&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:O,children:O})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&(T||J)||a==="interactive"&&(V||z)||a==="data"?l(he,{children:[J&&!T&&n("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:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:nt.background,border:`2px solid ${nt.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:nt.text},children:[n(Hr,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:nt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:nt.text},children:J})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(En,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[V&&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:[n(Su,{presets:[...An],customSizes:w,currentWidth:x.width,currentHeight:x.height??900,scale:N,onSizeChange:D,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:M}),e&&r&&l(se,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),V&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${An[An.length-1].width}px`,width:"100%"},children:n(_o,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:L,devicePresets:I})})}),n(lr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:V,isStarting:z,isLoading:$,showIframe:E,iframeKey:W,onIframeLoad:H,onScaleChange:k,onDimensionChange:S,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(mf,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(T||!J)&&n(Ye,{screenshotPath:T,cacheBuster:s,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!T?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("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"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),O&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:O})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):J?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(se,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:J})})]}),U&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:U})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(En,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):q.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:q,title:"Analysis Error",description:q.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${q.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(En,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),m&&c&&n(pt,{projectSlug:c,onClose:()=>f(!1)}),y&&n(Mo,{width:x.width,height:x.height??900,onSave:_,onCancel:()=>g(!1)})]})}function pf({analysis:e,entitySha:t}){ot();const[r,a]=P(e);ee(()=>{a(e)},[e]);const[s,o]=P(null),i=re(()=>{var p;if(!((p=r==null?void 0:r.metadata)!=null&&p.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(m=>{var f;return!((f=m.metadata)!=null&&f.sameAsDefault)});return da(r.metadata.executionFlows,u)},[r]),c=re(()=>i?Bu(i):[],[i]),d=re(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var p;return!((p=u.metadata)!=null&&p.sameAsDefault)}):[],[r]),h=u=>{var m;const p=((m=u.metadata)==null?void 0:m.coveredFlows)||[];return i?i.executionFlows.filter(f=>p.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),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]}),n("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),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("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."," ",n(se,{to:`/entity/${t}/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],m=h(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ye,{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:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(se,{to:`/entity/${t}/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)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),m.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:m.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(se,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),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:[n("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,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const p=s===u.id,m=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(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:[n("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:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),m?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),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:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),m&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function As({hasIndirectBadge:e,onAnalyze:t}){return l(he,{children:[n("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&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function ff({entity:e,history:t}){const[r,a]=P("entity"),[s,o]=P(new Set),i=t.filter(u=>u.analyses.length>0).length,c=re(()=>{const u=new Map;return t.forEach(p=>{p.analyses.forEach(m=>{(m.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:m,scenario:y})})})}),Array.from(u.entries()).map(([p,m])=>{var f;return{name:p,description:((f=m[0])==null?void 0:f.scenario.description)||"",versions:m.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,h=u=>{o(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),m})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("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 ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,p)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children: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)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(se,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((m,f)=>{var g;const y=(m.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(As,{hasIndirectBadge:m.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(he,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[m.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),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=m.metadata)==null?void 0:g.scenarioChangesOverview)&&n("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:"," "]}),m.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,v)=>{var N,k;const b=(k=(N=x.metadata)==null?void 0:N.screenshotPaths)==null?void 0:k[0],C=`${x.name}-${v}`;return l(se,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Ye,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},C)})})})]})},m.id||f)})}):n(As,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,p)=>{const m=s.has(u.name),f=m?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:[n("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:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var A,M;const{version:b,analysis:C,scenario:N}=x,k=(M=(A=N.metadata)==null?void 0:A.screenshotPaths)==null?void 0:M[0],w=v===0;return l("div",{className:`flex gap-5 items-start ${w?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(se,{to:`/entity/${b.sha}/scenarios/${N.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:k?n(Ye,{screenshotPath:k,alt:N.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),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)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),w&&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(se,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),C.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(C.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),C.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),y>0&&l("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${m?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),m?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function ks({entity:e,analysisInfo:t,from:r}){const a=Ae(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(se,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,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?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ye,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(Ve,{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:[n(Ve,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&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:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(he,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(he,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Ps=e=>{var s,o,i;const t=((s=e.analysisStatus)==null?void 0:s.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function gf({importedEntities:e,importingEntities:t}){const[r]=on(),a=r.get("from"),s=Ae(),o=s.state!=="idle",i=e.length>0,c=t.length>0,d=m=>m.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=m=>{const f=d(m);f.length!==0&&s.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,p=d(t).length>0;return n("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:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(m=>n(ks,{entity:m,analysisInfo:Ps(m),from:a},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),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:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),p&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(m=>n(ks,{entity:m,analysisInfo:Ps(m),from:a},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function yf({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(gf,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function xf({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(sn,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function sn({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,c]=P(r||t<2);if(ee(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):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(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>n("div",{className:"py-0.5",children:n(sn,{data:h,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,p=m=>Array.isArray(m)&&m.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:[h.length,"}"]})]}),i?l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(m=>{const f=e[m],y=u(f),g=p(f);return n("div",{className:"py-0.5",children:y?n(fa,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:a}):g?n(ga,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:a}):l(he,{children:[l("span",{className:"text-orange-600",children:[m,": "]}),n(sn,{data:f,depth:t+1,defaultExpanded:r,maxDepth:a})]})},m)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function fa({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=P(a||r<2),c=Object.keys(t);return ee(()=>{i(a||r<2)},[a,r]),l(he,{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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,p=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n(fa,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):p?n(ga,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):l(he,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(sn,{data:h,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function ga({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=P(a||r<2);return ee(()=>{i(a||r<2)},[a,r]),l(he,{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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const h=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:h?n(fa,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(ga,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):n(sn,{data:c,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function $r({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return l("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function _s({label:e,isActive:t,onClick:r,disabled:a=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Ms({call:e,scenarioName:t}){const[r,a]=P(!1),[s,o]=P("system"),i=m=>new Date(m).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=m=>m?`$${m.toFixed(4)}`:null,d=(m,f)=>{if(!m&&!f)return null;const y=[];return m&&y.push(`${m.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},h=re(()=>{var m,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(m=v.choices)==null?void 0:m[0])==null?void 0:f.message)!=null&&y.content?v.choices[0].message.content:(x=(g=v.content)==null?void 0:g[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=re(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),p=re(()=>{var m;if(t)return t;try{const f=JSON.parse(e.props);return((m=f==null?void 0:f.scenario)==null?void 0:m.name)||null}catch{return null}},[e.props,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),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:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),p&&n("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&&n("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:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("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"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),s==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),s==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),s==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Ts=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function bf({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var C,N,k,w,A,M,I,D,L;const[o,i]=P("entity"),[c,d]=P("analysis"),[h,u]=P(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[p,m]=P("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=re(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const _=[...s.entityCalls,...s.analysisCalls],S=_.filter(F=>F.object_type==="entity"||Ts.includes(F.prompt_type)),T=_.filter(F=>F.object_type!=="entity"&&!Ts.includes(F.prompt_type));return S.sort((F,q)=>q.created_at-F.created_at),T.sort((F,q)=>q.created_at-F.created_at),{entityLlmCalls:S,scenarioLlmCalls:T,totalLlmCalls:_.length}},[s]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(C=e==null?void 0:e.metadata)==null?void 0:C.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(w=(k=e==null?void 0:e.metadata)==null?void 0:k.isolatedDataStructure)==null?void 0:w.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(A=t==null?void 0:t.metadata)==null?void 0:A.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(M=e==null?void 0:e.metadata)==null?void 0:M.importedExports,"External Dependencies":(I=e==null?void 0:e.metadata)==null?void 0:I.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(D=t==null?void 0:t.metadata)==null?void 0:D.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(_=>_.data!==void 0&&_.data!==null).length;let b=null;if(o==="entity"){const _=x.find(S=>S.id===c);_&&_.data!==void 0&&_.data!==null&&(b={title:_.title,description:_.description,data:_.data})}else if(o==="scenarios"&&h){const _=r.find(S=>(S.id||S.name)===h.scenarioId);_&&(b={title:_.name,description:_.description||"Scenario data and configuration",data:_.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n($r,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n($r,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n($r,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((L=t==null?void 0:t.metadata)==null?void 0:L.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>m("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:()=>m("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,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:p==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(_=>n(Ms,{call:_},_.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(_=>n(Ms,{call:_},_.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(he,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(_=>{const S=_.data!==void 0&&_.data!==null;return n(_s,{label:_.title,isActive:c===_.id,onClick:()=>d(_.id),disabled:!S},_.id)})})]}):l(he,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(_=>{const S=_.id||_.name,T=(h==null?void 0:h.scenarioId)===S;return n(_s,{label:_.name,isActive:T,onClick:()=>u({scenarioId:S})},S)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(vf,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(js,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(js,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function js({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function vf({title:e,description:t,data:r}){const[a,s]=P(!0),[o,i]=P("Copy JSON");return l(he,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>s(!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"}),n("button",{onClick:()=>s(!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"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,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:o})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(xf,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function wf({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=Ae();return ee(()=>{if(e!=null&&e.sha&&s.state==="idle"&&!s.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(bf,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function Jo({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,h]=P(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{h(!0),setTimeout(()=>h(!1),s)}).catch(p=>{console.error("Failed to copy:",p)})},[e,s]);return n("button",{onClick:u,className:`cursor-pointer ${a}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(kt,{size:c,className:"text-green-500"}):n(Rt,{size:c}):d?r:t})}const Cf={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Nf={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Sf=2e3,Ef=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function Af({entity:e,entityCode:t}){const r=Jn(),a=Ne(null);return ee(()=>{const s=r.hash;if(!s||!a.current)return;const o=s.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[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)},[r.hash,t]),n("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:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(Jo,{content:t,label:"Copy Code",duration:Sf,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(jl,{language:Ef(e==null?void 0:e.filePath),style:Il,showLineNumbers:!0,customStyle:Cf,lineNumberStyle:Nf,wrapLines:!0,lineProps:s=>({"data-line-number":s,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const kf=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Pf({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:s,defaultShouldRevalidate:o}){return r.pathname===a.pathname&&r.search===a.search?o:!!(e.sha!==t.sha||s)}async function _f({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",h=c[1]||null,u=c[2]||null,p=r.analysisQueue,m=p?p.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Lt(a),$e(),Ot(),ld(ge()||process.cwd())]),v=f?await sa(f):null,b=f?await mo(f.sha):null;let C={importedEntities:[],importingEntities:[]},N=null,k=[];f&&(C=await po(f),N=await fo(f),k=await yo(f));const w=!!(f&&k.length>0&&k[0].sha!==f.sha),A=k.length>0?k[0].sha:null,M=!!(k.length>0&&k[0].analyses&&k[0].analyses.length>0),I=f?await go(f):!1;return B({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:o,relatedEntities:C,entityCode:N??void 0,hasNewerVersion:w,newestEntitySha:A,newestVersionHasAnalysis:M,fileModifiedSinceEntity:I,history:k,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:m})}const Mf=De(function(){var _a,Ma,Ta,ja,Ia,$a,Ra,Da,La,Fa,Oa,za,Ya,Ba,Ua;const t=Be(),s=(Fs()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,c=s[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,p=u||h,m=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,C=t.history,N=t.currentCommit,k=t.hasAnApiKey,w=t.queueState;(_a=p==null?void 0:p.status)==null||_a.errors;const A=(p==null?void 0:p.scenarios)||[],M=A.filter(ne=>{var xe;return!((xe=ne.metadata)!=null&&xe.sameAsDefault)}),I=A.filter(ne=>{var xe;return(xe=ne.metadata)==null?void 0:xe.sameAsDefault}),D=Tt(),L=Ne(null);ee(()=>{L.current===null&&(L.current=window.history.length)},[]);const _=()=>{if(typeof window>"u")return;const ne=window.history.state;if(ne===null||(ne==null?void 0:ne.idx)===void 0||(ne==null?void 0:ne.idx)===0)D("/");else{const xe=window.history.length,He=L.current;if(He!==null&&xe>He){const _e=xe-He+1;D(-_e)}else D(-1)}},S=!!w.currentlyExecuting,T=o,F=(Ma=N==null?void 0:N.metadata)==null?void 0:Ma.currentRun,q=!!(F!=null&&F.createdAt)&&!(F!=null&&F.analysisCompletedAt),J=!!(d!=null&&d.sha&&((Ta=F==null?void 0:F.currentEntityShas)!=null&&Ta.includes(d.sha))),U=!!(d!=null&&d.sha&&((Ia=(ja=w.currentlyExecuting)==null?void 0:ja.entityShas)!=null&&Ia.includes(d.sha))),Y=!!(d!=null&&d.sha&&(($a=w.jobs)!=null&&$a.some(ne=>{var xe;return(xe=ne.entityShas)==null?void 0:xe.includes(d.sha)}))),z=J||U||Y,$=z&&((Ra=p==null?void 0:p.status)==null?void 0:Ra.finishedAt)!=null&&M.length>0&&p.entitySha!==(d==null?void 0:d.sha),E=re(()=>{if(T!=="scenarios")return null;if(i){const ne=M.find(xe=>xe.id===i);if(ne)return ne}return M.length>0&&!z?M[0]:null},[T,i,M,z]),W=((Fa=(La=(Da=E==null?void 0:E.metadata)==null?void 0:Da.executionResult)==null?void 0:La.error)==null?void 0:Fa.message)||((Ya=(za=(Oa=p==null?void 0:p.status)==null?void 0:Oa.errors)==null?void 0:za[0])==null?void 0:Ya.message);Xe({source:E?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:E==null?void 0:E.id,analysisId:p==null?void 0:p.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:E==null?void 0:E.name,errorMessage:W});const[H,V]=P(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ee(()=>{c&&c!==H&&c!=="edit"&&V(c)},[c]);const ae=c==="edit",[O,j]=P(!1),[R,G]=P(!1),[te,ce]=P(null),[pe,me]=P(!1),[be,Ce]=P(!1),[Ee,Se]=P(null),[Pe,Te]=P(null),[ve,Q]=P(0),{interactiveServerUrl:ue,isStarting:ye,isLoading:bt,showIframe:de,iframeKey:Fe,onIframeLoad:Oe}=mn({analysisId:p==null?void 0:p.id,scenarioId:E==null?void 0:E.id,scenarioName:E==null?void 0:E.name,projectSlug:m,enabled:ae&&!!E,refreshTrigger:ve}),[Bt,y0]=P(!1),[x0,b0]=P(""),[pn,Ut]=P(!1),[Ea,pr]=P(Date.now()),[li,fr]=P(!1),et=Ae(),vt=Ae(),We=Ae(),ze=ot(),ci=w.jobs.some(ne=>{var xe;return(d==null?void 0:d.sha)&&((xe=ne.entityShas)==null?void 0:xe.includes(d.sha))||ne.type==="analysis"&&ne.commitSha===(N==null?void 0:N.sha)&&ne.entityShas&&ne.entityShas.length===0}),gr=z,Aa=((Ba=d==null?void 0:d.metadata)==null?void 0:Ba.defaultWidth)||((Ua=p==null?void 0:p.metadata)==null?void 0:Ua.defaultWidth)||1440,di=Math.round(Aa*(900/1440));et.state==="submitting"||et.state,re(()=>{var ne;return!!((ne=E==null?void 0:E.metadata)!=null&&ne.interactiveExamplePath)},[E]);const{isCompleted:ka}=gt(m,pn);ee(()=>{et.state==="idle"&&et.data&&(et.data.success?setTimeout(()=>{pr(Date.now()),ze.revalidate(),Ut(!1)},1500):et.data.error&&(Ut(!1),alert(`Recapture failed: ${et.data.error}`)))},[et.state,et.data,ze]),ee(()=>{pn&&ka&&setTimeout(()=>{pr(Date.now()),ze.revalidate(),Ut(!1)},1500)},[pn,ka,ze]),ee(()=>{vt.state==="idle"&&vt.data&&(vt.data.success?setTimeout(()=>{pr(Date.now()),ze.revalidate(),Ut(!1)},1500):vt.data.error&&(Ut(!1),alert(`Recapture failed: ${vt.data.error}`)))},[vt.state,vt.data,ze]);const Pa=()=>{d&&(g&&x&&x!==d.sha?(D(`/entity/${x}/scenarios`),setTimeout(()=>{We.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):We.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ee(()=>{We.state==="idle"&&We.data&&(We.data.success?ze.revalidate():We.data.error&&alert(`Analysis failed: ${We.data.error}`))},[We.state,We.data,d==null?void 0:d.sha,ze]),ee(()=>{const ne=setTimeout(()=>{ze.revalidate()},500);return()=>clearTimeout(ne)},[]),ee(()=>{if(q||gr){const ne=setInterval(()=>{ze.revalidate()},3e3);return()=>clearInterval(ne)}else{const ne=setInterval(()=>{ze.revalidate()},5e3),xe=setTimeout(()=>{clearInterval(ne)},3e4);return()=>{clearInterval(ne),clearTimeout(xe)}}},[q,gr,ze]);const ui=(ne,xe)=>ne==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ne}`,hi=(ne,xe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ne}/${xe}`,mi=ne=>{V(ne),E!=null&&E.id&&(ne==="interactive"?D(`/entity/${d==null?void 0:d.sha}/scenarios/${E.id}/fullscreen`,{replace:!0}):D(hi(E.id,ne),{replace:!0}))},pi=async ne=>{var xe,He;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ne,hasSelectedScenario:!!E,hasAnalysis:!!p}),!E||!p){const _e="Error: No scenario or analysis available";console.error("[EntityDetail]",_e),ce(_e);return}j(!0),ce(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ne,scenarioId:E.id,scenarioName:E.name,currentData:E.data});try{const _e=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ne,existingScenarios:p.scenarios,scenariosDataStructure:(xe=p.metadata)==null?void 0:xe.scenariosDataStructure,editingMockName:E.name,editingMockData:Pe||((He=E.metadata)==null?void 0:He.data)})}),tt=await _e.json();if(!_e.ok||!tt.success)throw new Error(tt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",tt.data),Te(tt.data);const fn=(p.scenarios||[]).map(Ue=>Ue.id===E.id?{...Ue,metadata:{...Ue.metadata,data:tt.data}}:Ue),Wt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:fn})}),Ge=await Wt.json();if(!Wt.ok||!Ge.success)throw console.error("[EntityDetail] Temp save failed:",Ge),new Error(Ge.error||"Failed to apply preview");if(ce("Generating preview. Capturing screenshot..."),ue){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ue});const Ue=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ue,scenarioId:E.id,projectId:p.projectId,viewportWidth:1440})}),Ht=await Ue.json();!Ue.ok||!Ht.success?(console.error("[EntityDetail] Direct capture failed:",Ht),ce("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ce('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ue=new FormData;Ue.append("analysisId",p.id||""),Ue.append("scenarioId",E.id||"");const Ht=await fetch("/api/recapture-scenario",{method:"POST",body:Ue}),xr=await Ht.json();!Ht.ok||!xr.success?(console.warn("[EntityDetail] Recapture failed:",xr.error),ce("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",xr.jobId),ce('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}Q(Ue=>Ue+1),ze.revalidate()}catch(_e){console.error("Error applying changes:",_e),ce(`Error: ${_e instanceof Error?_e.message:String(_e)}`)}finally{j(!1)}},fi=async(ne,xe)=>{var He;if(!E||!p){ce("Error: No scenario or analysis available");return}G(!0),ce(null),console.log("[EntityDetail] Saving scenario to database",{description:ne,saveAsNew:xe});try{const _e=Pe||((He=E.metadata)==null?void 0:He.data);let tt;if(xe){const Ge={...E,id:`${E.name}-${Date.now()}`,name:`${E.name} (Copy)`,metadata:{...E.metadata,data:_e},description:ne||E.description};tt=[...p.scenarios||[],Ge]}else tt=(p.scenarios||[]).map(Ge=>Ge.id===E.id?{...Ge,metadata:{...Ge.metadata,data:_e},description:ne||Ge.description}:Ge);const fn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:tt})}),Wt=await fn.json();if(!fn.ok||!Wt.success)throw new Error(Wt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ce(xe?"New scenario created successfully":"Scenario saved successfully"),Te(null),ze.revalidate()}catch(_e){console.error("Error saving scenario:",_e),ce(`Error: ${_e instanceof Error?_e.message:String(_e)}`)}finally{G(!1)}},gi=()=>{console.log("[EntityDetail] Edit mock data clicked"),ce("Mock data editor coming soon")},yi=async()=>{var ne;if(!(E!=null&&E.id)){Se("Cannot delete scenario without ID");return}me(!0),Se(null);try{const xe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:E.id,screenshotPaths:((ne=E.metadata)==null?void 0:ne.screenshotPaths)||[]})}),He=await xe.json();if(!xe.ok||!He.success)throw new Error(He.error||"Failed to delete scenario");D(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(xe){console.error("[EntityDetail] Error deleting scenario:",xe),Se(xe instanceof Error?xe.message:"Failed to delete scenario"),Ce(!1)}finally{me(!1)}},yr=p&&d&&p.entitySha!==d.sha,xi=d?df(d):!1;return n(ir,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("button",{onClick:_,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:M.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(ne=>n(se,{to:ui(ne.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${T===ne.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:T===ne.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[ne.label,ne.count!==void 0&&ne.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${T===ne.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ne.count})]})},ne.id))})]})}),(g||yr&&!u||b&&xi)&&!z&&!ci&&n("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:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:yr&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":yr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&v?n(se,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:ne=>{ne.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ne=>{ne.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Pa,disabled:We.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:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[T==="scenarios"&&l(he,{children:[ae&&E?n(hf,{scenario:E,entitySha:(d==null?void 0:d.sha)||"",onApply:pi,onSave:fi,onEditMockData:gi,onDelete:yi,isApplying:O,isSaving:R,saveMessage:te,showDeleteConfirm:be,onShowDeleteConfirm:Ce,isDeleting:pe,deleteError:Ee}):n(uf,{scenarios:M,hiddenScenarios:I,analysis:p,selectedScenario:E,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:Ea,activeTab:T,entityType:d==null?void 0:d.entityType,entity:d,queueState:w,processIsRunning:S,isEntityAnalyzing:z,areScenariosStale:$,viewMode:H,setViewMode:mi,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(pf,{analysis:p??null,entitySha:(d==null?void 0:d.sha)||""}):ae&&E?n(lr,{scenarioId:E.id||E.name,scenarioName:E.name,iframeUrl:ue,isStarting:ye,isLoading:bt,showIframe:de,iframeKey:Fe,onIframeLoad:Oe,projectSlug:m,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[E&&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:[n("span",{className:"text-xs font-semibold text-[#343434]",children:E.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Aa," × ",di]})]}),l("div",{className:"flex items-center gap-2",children:[n(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${E.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:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${E.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Vo,{selectedScenario:E,analysis:p,entity:d,viewMode:H,cacheBuster:Ea,hasScenarios:M.length>0,isAnalyzing:gr,projectSlug:m,hasAnApiKey:k,processIsRunning:S,queueState:w})]})]}),T==="related"&&n(yf,{relatedEntities:f}),T==="data"&&n(wf,{entity:d,analysis:p,scenarios:M,onAnalyze:Pa}),T==="code"&&n(Af,{entity:d,entityCode:y}),T==="history"&&n(ff,{entity:d,history:C})]}),li&&m&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>fr(!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:ne=>ne.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>fr(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(pt,{projectSlug:m,onClose:()=>fr(!1)})})]})})]})})}),Tf=Object.freeze(Object.defineProperty({__proto__:null,default:Mf,loader:_f,meta:kf,shouldRevalidate:Pf},Symbol.toStringTag,{value:"Module"}));async function jf(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:s,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Le();const i=ge();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=ie.join(i,".codeyam","config.json"),d=JSON.parse(await fe.readFile(c,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const p=ar(h);try{await fe.writeFile(p,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:m,branch:f}=await Ie(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await at({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(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 x=await sd(m,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await mt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const C=b.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&gd(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:h,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function If({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await dt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),c=a.get("context"),d=a.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(s)h=[s];else return B({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return B({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await at({shas:h}),m=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await jf({entityShas:h,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),B({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:m,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),B({error:"Failed to start analysis",details:a.message},{status:500})}}const $f=Object.freeze(Object.defineProperty({__proto__:null,action:If},Symbol.toStringTag,{value:"Module"}));function Rf(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:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Go(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const s=t.getHours(),o=t.getMinutes(),i=s>=12?"pm":"am",c=s%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function qe(e,t=[],r=!1){var u,p;if(t.some(m=>{var f,y;return!!((f=m.entityShas)!=null&&f.includes(e.sha)||(y=m.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const s=e.analyses[0];if(!(((u=s.status)==null?void 0:u.scenarios)&&s.status.scenarios.length>0&&s.status.scenarios.some(m=>m.screenshotFinishedAt||m.finishedAt))||s.entitySha!==e.sha)return"not-analyzed";const i=s.createdAt?new Date(s.createdAt).getTime():0,c=(p=e.metadata)!=null&&p.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],h=d.some(m=>{var f,y,g;return((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=m.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&h?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Df=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Lf({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await un();return B({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),B({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Ff=De(function(){const t=Be(),r=t.entities,a=t.queueState;Xe({source:"simulations-page"});const[s,o]=P(""),[i,c]=P("visual"),d=re(()=>{const g=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const C=v.scenarios.filter(N=>{var k;return!((k=N.metadata)!=null&&k.sameAsDefault)}).map(N=>{var L,_,S,T,F;const k=(_=(L=N.metadata)==null?void 0:L.screenshotPaths)==null?void 0:_[0],w=(S=N.metadata)==null?void 0:S.noScreenshotSaved,A=k&&!w,M=(F=(T=v.status)==null?void 0:T.scenarios)==null?void 0:F.find(q=>q.name===N.name),I=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt;let D;return A?D="completed":I?D="capturing":D="error",{scenarioName:N.name,scenarioDescription:N.description||"",screenshotPath:k||"",scenarioId:N.id,state:D}}).filter(N=>N.state==="completed"||N.state==="capturing");C.length>0&&g.push({entity:x,screenshots:C,createdAt:v.createdAt||""})}}),g.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),h=re(()=>r.filter(g=>{var b,C;const x=(b=g.analyses)==null?void 0:b[0];return!((C=x==null?void 0:x.scenarios)==null?void 0:C.some(N=>{var k,w;return(w=(k=N.metadata)==null?void 0:k.screenshotPaths)==null?void 0:w[0]}))}),[r]),u=re(()=>d.filter(({entity:g})=>{const x=!s||g.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[d,s,i]),p=re(()=>h.filter(g=>{const x=!s||g.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[h,s,i]),m=oe(g=>{o(g.target.value)},[]),f=oe(g=>{c(g.target.value)},[]),y=d.length>0;return n("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:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),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:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(st,{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:[n(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:s,onChange:m})]})]})]}),y&&u.length>0&&n("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:[n("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:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(he,{children:u.map(({entity:g,screenshots:x})=>n(Of,{entity:g,screenshots:x,queueJobs:(a==null?void 0:a.jobs)||[]},g.sha))})),!y&&(p.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):p.map(g=>n(zf,{entity:g},g.sha)))]})]})})});function Of({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const a=Tt(),s=Ae(),[o,i]=P(!1),c=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{a(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},h=()=>{i(!0),s.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ee(()=>{s.state==="idle"&&o&&i(!1)},[s.state,o]);const u=qe(e,r),p=Rf(u),m=u==="out-of-date";return n("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:[n("div",{className:"flex-shrink-0",children:n(Ve,{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(se,{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,")"]}),n("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})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[m&&n(he,{children:o||s.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:h,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void 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:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ye,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(pa,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children: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:[x.scenarioName,x.scenarioDescription&&l(he,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function zf({entity:e}){const t=Ae(),[r,a]=P(!1),s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ee(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:s,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:[n(Ve,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(se,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:Go(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.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:[n(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:s,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 Yf=Object.freeze(Object.defineProperty({__proto__:null,default:Ff,loader:Lf,meta:Df},Symbol.toStringTag,{value:"Module"}));function Bf({request:e,context:t}){const r=t.dbNotifier||Or;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(s){const o=new TextEncoder;s.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
229
-
230
- `)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
231
-
232
- `))}catch{c()}};r.on("change",d);const h=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
233
-
234
- `))}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 Uf=Object.freeze(Object.defineProperty({__proto__:null,loader:Bf},Symbol.toStringTag,{value:"Module"}));function Wf(){return new Response(JSON.stringify({status:"ok",version:la,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const Hf=Object.freeze(Object.defineProperty({__proto__:null,loader:Wf},Symbol.toStringTag,{value:"Module"}));function ya(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const a=r[1],s=r[2],o={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);i&&(o.paths=i[1].split(`
235
- `).filter(d=>d.trim().startsWith("-")).map(d=>d.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean));const c=a.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:s}}async function ur(e,t=""){const r=[];try{const a=await fe.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){const i=await ur(ie.join(e,s.name),o);r.push(...i)}else s.isFile()&&s.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function hr(e){const t=await ur(e),r=[];for(const a of t){const s=ie.join(e,a);try{const o=await fe.readFile(s,"utf-8"),{frontmatter:i,body:c}=ya(o);r.push({filePath:a,absolutePath:s,frontmatter:i,body:c})}catch{}}return r}function Vf(e,t){return!t.frontmatter.paths||t.frontmatter.paths.length===0?!1:t.frontmatter.paths.some(r=>Js(e,r,{matchBase:!0}))}const Jf="codeyam-rule-state.json",Rr=1;function qo(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return qn.createHash("sha256").update(t).digest("hex")}function Ko(e){return ie.join(e,".claude",Jf)}async function Qo(e){const t=Ko(e);try{const r=await fe.readFile(t,"utf-8"),a=JSON.parse(r);return a.version!==Rr?(console.warn(`[ruleState] Unknown version ${a.version}, using empty state`),{version:Rr,rules:{}}):a}catch{return{version:Rr,rules:{}}}}async function Zo(e,t){const r=Ko(e),a=ie.dirname(r);await fe.mkdir(a,{recursive:!0}),await fe.writeFile(r,JSON.stringify(t,null,2)+`
236
- `,"utf-8")}async function xa(e,t){const r=await Qo(e),a=new Set(t.map(s=>s.filePath));for(const s of Object.keys(r.rules))a.has(s)||delete r.rules[s];for(const s of t){const o=await fe.readFile(s.absolutePath,"utf-8"),i=qo(o),c=r.rules[s.filePath];c?c.contentHash!==i&&(r.rules[s.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[s.filePath]={contentHash:i,reviewed:!1}}return await Zo(e,r),r}async function Is(e,t,r,a){const s=await Qo(e);if(r){const o=ie.join(e,".claude","rules"),i=ie.join(o,t),c=await fe.readFile(i,"utf-8"),d=qo(c);s.rules[t]?(s.rules[t].reviewed=!0,s.rules[t].contentHash=d):s.rules[t]={contentHash:d,reviewed:!0}}else s.rules[t]&&(s.rules[t].reviewed=!1);await Zo(e,s)}function ba(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Xo(e,t=""){const r=[],a=await fe.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;s.isDirectory()?r.push(...await Xo(ie.join(e,s.name),o)):s.name.endsWith(".md")&&r.push(o)}return r}function ei(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
237
- `).filter(a=>!(!a.startsWith("+")&&!a.startsWith("-")||a.startsWith("+++")||a.startsWith("---"))).map(a=>a.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(a=>r.test(a))}async function Gf({request:e}){const t=ge();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),a=r.searchParams.get("action"),s=ie.join(t,".claude","rules");if(a==="recent-changes")return Kf(t,s);if(a==="reviewed-status")return Qf(t,s);if(a==="audit")return Zf(t,s);if(a==="source-files")return Xf(t);if(a==="rules-for-path"){const o=r.searchParams.get("path");return o?eg(s,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await ur(s),i=[];for(const p of o){const m=ie.join(s,p);try{const f=await fe.readFile(m,"utf-8"),y=await fe.stat(m),{frontmatter:g,body:x}=ya(f);i.push({filePath:p,content:f,frontmatter:g,body:x,lastModified:y.mtime.toISOString()})}catch{}}i.sort((p,m)=>new Date(m.lastModified).getTime()-new Date(p.lastModified).getTime());let c=i.length>0;if(!c)try{await fe.access(ie.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await hr(s),h=await xa(t,d),u={};for(const p of d)u[p.filePath]=ba(h,p.filePath);return Response.json({memories:i,memoryInitialized:c,reviewedStatus:u})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function qf(e,t){const r=[];try{const a=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const s of a.split(`
238
- `).filter(Boolean)){const o=s.substring(0,2);let i=s.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let h=[i];if(i.endsWith("/")&&c==="?"){const u=ie.join(e,i);try{h=(await Xo(u)).map(m=>i+m)}catch{continue}}for(const u of h){if(u.endsWith("/"))continue;const p=u.replace(".claude/rules/","");let m="modified";c==="A"||c==="?"?m="added":c==="D"||d==="D"?m="deleted":(c==="M"||d==="M")&&(m="modified");let f="";try{if(m==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(m==="added"&&c==="?"){const y=`${e}/${u}`;try{const g=await fe.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
239
- new file mode 100644
240
- --- /dev/null
241
- +++ b/${u}
242
- @@ -0,0 +1,${g.split(`
243
- `).length} @@
244
- ${g.split(`
245
- `).map(x=>"+"+x).join(`
246
- `)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
247
- ... (truncated)`)}catch{f="(diff not available)"}m==="modified"&&ei(f)||r.push({filePath:p,changeType:m,diff:f})}}}catch{}return r}async function Kf(e,t){try{const{execSync:r}=await import("child_process"),a=[],s=await hr(t),o=await xa(e,s),i={};for(const p of s)i[p.filePath]=ba(o,p.filePath);const d=(await qf(e,r)).filter(p=>!i[p.filePath]);d.length>0&&a.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:d});const u=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
248
- `).filter(Boolean).slice(0,20);for(const p of u){const[m,f,...y]=p.split("|"),g=y.join("|");if(!m||!f)continue;const x=r(`git diff-tree --no-commit-id --name-status -r ${m} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),v=[];for(const b of x.split(`
249
- `).filter(Boolean)){const[C,N]=b.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const k=N.replace(".claude/rules/","");let w="modified";if(C==="A"?w="added":C==="D"&&(w="deleted"),i[k])continue;let A="";try{A=r(`git show ${m} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),A.length>5e3&&(A=A.substring(0,5e3)+`
250
- ... (truncated)`)}catch{A="(diff not available)"}w==="modified"&&ei(A)||v.push({filePath:k,changeType:w,diff:A})}v.length>0&&a.push({commitHash:m.substring(0,8),date:f,message:g,files:v})}return Response.json({changes:a,reviewedStatus:i})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function Qf(e,t){try{const r=await hr(t),a=await xa(e,r),s={};for(const o of r)s[o.filePath]=ba(a,o.filePath);return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function ti(e){const t=[],r=[".ts",".tsx",".js",".jsx",".vue",".svelte"];async function a(s,o){try{const i=await fe.readdir(s,{withFileTypes:!0});for(const c of i){const d=ie.join(s,c.name),h=o?`${o}/${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,h);else if(c.isFile()){const u=ie.extname(c.name);r.includes(u)&&t.push(h)}}}}catch{}}return await a(e,""),t}async function Zf(e,t){try{const r=await hr(t),a=await ti(e),s=[];for(const o of a){const i=r.filter(c=>Vf(o,c));if(i.length>0){const c=i.reduce((d,h)=>d+h.body.length,0);s.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return s.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:s,totalFilesWithCoverage:s.length,allSourceFiles:a})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Xf(e){try{const t=await ti(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function eg(e,t){try{const r=await ur(e),a=[];for(const o of r){const i=ie.join(e,o);try{const c=await fe.readFile(i,"utf-8"),d=await fe.stat(i),{frontmatter:h,body:u}=ya(c);h.paths&&h.paths.some(p=>Js(t,p,{matchBase:!0}))&&a.push({filePath:o,content:c,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const s=a.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:a,totalTextLength:s})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function tg({request:e}){const t=ge();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ie.join(t,".claude","rules");try{const a=await e.json(),{action:s,filePath:o,content:i,lastModified:c}=a;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(s==="mark-reviewed")return await Is(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(s==="mark-unreviewed")return await Is(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=ie.normalize(o);if(d.includes("..")||ie.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=ie.join(r,d);switch(s){case"create":case"update":return i?(await fe.mkdir(ie.dirname(h),{recursive:!0}),await fe.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${s}d: ${o}`),Response.json({success:!0,message:`Memory ${s}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await fe.unlink(h),console.log(`[API] Memory deleted: ${o}`);const u=ie.dirname(h);try{(await fe.readdir(u)).length===0&&u!==r&&await fe.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(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 ng=Object.freeze(Object.defineProperty({__proto__:null,action:tg,loader:Gf},Symbol.toStringTag,{value:"Module"}));async function rg({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await dt()),!r)return B({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return B({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return B({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return B({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 B({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?B({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):B({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const p=h.entityShas.map(f=>Lt(f)),m=await Promise.all(p);u.push(...m.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const p=h.entityShas.map(f=>Lt(f)),m=await Promise.all(p);u.push(...m.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return B({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return B({error:"Unknown queryType"},{status:400})}async function ag({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await dt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),B({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:s,...o}=a;if(console.log("[Queue API] Action:",s,"Params:",Object.keys(o)),s==="enqueue"){const{jobId:i,completion:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),B({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),B({status:"resumed"});if(s==="pause")return r.pause(),B({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?B({status:"removed",jobId:i}):B({error:"Job not found in queue"},{status:404}):B({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return B({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?B({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?B({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?B({status:"reordered",jobId:i,direction:c}):B({error:"Could not reorder job (not found or at boundary)"},{status:400})}return B({error:"Unknown action"},{status:400})}const sg=Object.freeze(Object.defineProperty({__proto__:null,action:ag,loader:rg},Symbol.toStringTag,{value:"Module"})),og=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],ig=De(function(){return Ae(),n(ir,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),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:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children: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",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),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",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Vo,{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})]})]})})}),lg=Object.freeze(Object.defineProperty({__proto__:null,default:ig,meta:og},Symbol.toStringTag,{value:"Module"})),cg=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function dg({request:e}){var t,r;try{const a=await nr();if(!a)return B({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let s=!1;try{const d=await $e();if(d){const{project:h}=await Ie(d);s=((r=(t=h.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=ge()||process.cwd(),i=await rr(o),c=Ao(a.projectSlug);return B({config:a,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:c,simulationsEnabled:s,error:null})}catch(a){return console.error("Failed to load config:",a),B({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function ug(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],a=t.length>1?t.slice(1):void 0;return{command:r,args:a}}async function hg({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),s=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let h;if(r)try{h=JSON.parse(r)}catch{return B({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(a)try{u=JSON.parse(a)}catch{return B({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let p;c&&(p=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let m;if(d)try{m=JSON.parse(d)}catch{return B({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await nr();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const C=ug(u[b]);return{...v,startCommand:C}}return v}))}if(!await xo({universalMocks:h,pathsToIgnore:p,webapps:f,memory:m}))return B({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(s!==void 0||o!==void 0||i!==void 0){const x=ge()||process.cwd(),v=await rr(x);g=s!==void 0&&s!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await id(x,{...v,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return B({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),B({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function $s(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Rs({mock:e,onSave:t,onCancel:r}){const[a,s]=P(e.entityName),[o,i]=P(e.filePath),[c,d]=P(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:u=>s(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:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("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:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function mg(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const pg=De(function(){var Ee,Se,Pe,Te,ve;const{config:t,secrets:r,versionInfo:a,simulationsEnabled:s,error:o}=Be(),i=Ti(),c=Ae(),d=ot(),[h,u]=P(s?"project-metadata":"memory");Xe({source:"settings-page"});const[p,m]=P((t==null?void 0:t.universalMocks)||[]),[f,y]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=P((r==null?void 0:r.GROQ_API_KEY)||""),[C,N]=P((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[k,w]=P((r==null?void 0:r.OPENAI_API_KEY)||""),[A,M]=P(!1),[I,D]=P(!1),[L,_]=P(!1),[S,T]=P(!1),[F,q]=P(!1),[J,U]=P(!1),[Y,z]=P(null),[$,E]=P(!1),[W,H]=P({}),[V,ae]=P(((Ee=t==null?void 0:t.memory)==null?void 0:Ee.conversationReflection)??!0),[O,j]=P(((Se=t==null?void 0:t.memory)==null?void 0:Se.ruleMaintenance)??!0),[R,G]=P(((Pe=t==null?void 0:t.memory)==null?void 0:Pe.promptModel)??"haiku");ee(()=>{var Q,ue,ye,bt;if(t){m(t.universalMocks||[]);const de=(t.pathsToIgnore||[]).join(", ");y(de),x(de);const Fe={};(Q=t.webapps)==null||Q.forEach((Oe,Bt)=>{Oe.startCommand&&(Fe[Bt]=$s(Oe.startCommand))}),H(Fe),ae(((ue=t.memory)==null?void 0:ue.conversationReflection)??!0),j(((ye=t.memory)==null?void 0:ye.ruleMaintenance)??!0),G(((bt=t.memory)==null?void 0:bt.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),N(r.ANTHROPIC_API_KEY||""),w(r.OPENAI_API_KEY||""))},[t,r]),ee(()=>{if(i!=null&&i.success){T(!0);const Q=setTimeout(()=>T(!1),3e3);return()=>clearTimeout(Q)}},[i]),ee(()=>{if(c.state==="idle"&&c.data&&!J){console.log("[Settings] Fetcher data:",c.data);const Q=c.data;if(Q.success){console.log("[Settings] Save successful, revalidating..."),T(!0),U(!0),(f!==g||Q.requiresRestart)&&q(!0),d.revalidate();const ue=setTimeout(()=>{T(!1),U(!1)},3e3);return()=>clearTimeout(ue)}}},[c.state,c.data,J,d,f,g]);const te=Q=>{Q.preventDefault();const ue=new FormData(Q.currentTarget);ue.set("universalMocks",JSON.stringify(p)),ue.set("startCommands",JSON.stringify(W)),ue.set("memorySettings",JSON.stringify({conversationReflection:V,ruleMaintenance:O,promptModel:R})),console.log("[Settings] Submitting form data:",{universalMocks:ue.get("universalMocks"),startCommands:ue.get("startCommands"),openAiApiKey:ue.get("openAiApiKey")?"***":"(empty)"}),c.submit(ue,{method:"post"})},ce=Q=>{m([...p,Q]),E(!1)},pe=(Q,ue)=>{const ye=[...p];ye[Q]=ue,m(ye),z(null)},me=Q=>{m(p.filter((ue,ye)=>ye!==Q))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const be=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Ce=s?be:be.filter(Q=>Q.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.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:c.state==="submitting"?"Saving...":"Save Settings"})]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(Q=>n("li",{children:n("button",{type:"button",onClick:()=>u(Q.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${h===Q.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:Q.label})},Q.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:te,className:"space-y-6",children:[h==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((Q,ue)=>{var ye;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[Q.startCommand.command," ",(ye=Q.startCommand.args)==null?void 0:ye.join(" ")]})]})]})},ue)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),h==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:Q=>b(Q.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>M(!A),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:A?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:I?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:C,onChange:Q=>N(Q.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>D(!I),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:I?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:L?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:k,onChange:Q=>w(Q.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>_(!L),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:L?"Hide":"Show"})]})]})]})]})]}),h==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((Q,ue)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:Q.path==="."?"Root":Q.path}),n("div",{className:"text-sm text-gray-600",children:Q.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${ue}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ue}`,name:`startCommand-${ue}`,value:W[ue]||"",onChange:ye=>H({...W,[ue]:ye.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},ue))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),h==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:Q=>y(Q.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:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),h==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),p.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>E(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:p.map((Q,ue)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:Y===ue?n(Rs,{mock:Q,onSave:ye=>pe(ue,ye),onCancel:()=>z(null)}):n(he,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:Q.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:Q.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:Q.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>z(ue),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>me(ue),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ue))}),p.length>0&&n("button",{type:"button",onClick:()=>E(!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"})]}),h==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":V,onClick:()=>ae(!V),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${V?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${V?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":O,onClick:()=>j(!O),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${O?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${O?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(Q=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${R===Q.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:Q.value,checked:R===Q.value,onChange:()=>G(Q.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:Q.label}),Q.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:Q.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:Q.description})]})]},Q.value))})]})]})]}),h==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((Q,ue)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:$s(Q.startCommand)})]})]})},ue))})]})]}),a&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((Te=a.templateVersion.gitCommit)==null?void 0:Te.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",mg(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((ve=a.cachedAnalyzerVersion.gitCommit)==null?void 0:ve.slice(0,7))||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(S||F||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[S&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),F&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(c.data&&typeof c.data=="object"&&"error"in c.data){const Q=c.data;return typeof Q.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:Q.error}):null}return null})()]}),$&&n("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:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Rs,{mock:{entityName:"",filePath:"",content:""},onSave:ce,onCancel:()=>E(!1)})]})})]})})}),fg=Object.freeze(Object.defineProperty({__proto__:null,action:hg,default:pg,loader:dg,meta:cg},Symbol.toStringTag,{value:"Module"}));async function gg({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=ge();if(!r)return new Response("Project root not found",{status:500});const s=ie.extname(t)!==""?t:`${t}.html`,o=ie.join(r,".codeyam","captures","static",s);try{await fe.access(o);let i=await fe.readFile(o);const c=ie.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const m=u[1].match(/=\s*(\{[\s\S]*\})/);if(m){const f=JSON.parse(m[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],y)}}catch(p){console.error("[Static] Failed to parse Remix context:",p)}i=Buffer.from(h,"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 yg=Object.freeze(Object.defineProperty({__proto__:null,loader:gg},Symbol.toStringTag,{value:"Module"}));function xg(e,t,r=10){var d;const a=new Map,s=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)s(h)&&a.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const p of Object.keys(u))for(const m of Object.keys(u[p])){const{shas:f}=u[p][m];for(const y of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(y)}}const i=[],c=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),c.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const p=o.get(h);if(p)for(const m of p){if(c.has(m))continue;c.add(m);const f=t.find(y=>y.sha===m);if(f){if(s(f)){const y=u+1,g=a.get(m);(!g||y<g.depth)&&a.set(m,{entity:f,depth:y})}i.push({sha:m,depth:u+1})}}}return Array.from(a.values()).sort((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function Hn(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const s=a.sort((o,i)=>{var h,u;const c=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(s[0])}return r}function ni(e,t){const r=new Map,a=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&a.add(s.oldPath);for(const s of e){const o=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),i=o.filter(d=>{var h,u;return a.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=Hn(i);r.set(s.path,{status:s,entities:o,editedEntities:c})}return r}function bg(e,t,r){const a=new Map;if(!r){for(const o of e)if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),c=Hn(i);a.set(o.path,{status:o,entities:c})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&s.set(o.filePath,i)}for(const o of e){const i=s.get(o.path);if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const c=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=Hn(c);a.set(o.path,{status:o,entities:d})}}return a}function vg(e,t){const r=new Map,a=ri(e,t);for(const s of a){const i=xg([s],t).filter(({depth:c})=>c>0);r.set(s.sha,i)}return r}function ri(e,t){const r=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&r.add(s.oldPath);const a=t.filter(s=>{var o,i;return r.has(s.filePath)&&((o=s.metadata)==null?void 0:o.isUncommitted)&&!((i=s.metadata)!=null&&i.isSuperseded)});return Hn(a)}function wg({recentSimulations:e}){const t=re(()=>{const r=new Map;return e.forEach(a=>{const s=a.entitySha,o=r.get(s);o?o.push(a):r.set(s,[a])}),Array.from(r.entries()).map(([a,s])=>({entitySha:a,entityName:s[0].entityName,scenarios:s}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(he,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(tn,{size:16,style:{color:"#8B5CF6"}})}),n(se,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((a,s)=>n(se,{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:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:n(Ye,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${s}`))})]},r.entitySha))}),n(se,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):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:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(tn,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(se,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(se,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Cg="/assets/codeyam-name-logo-CvKwUgHo.svg",Ng=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Sg({request:e,context:t}){var r,a,s,o;try{const i=await $e();if(i){const{project:_}=await Ie(i);if(!(((a=(r=_.metadata)==null?void 0:r.labs)==null?void 0:a.simulations)??!1))return ji("/memory")}const c=t.analysisQueue,d=c?c.getState():{paused:!1,jobs:[]},[h,u]=await Promise.all([un(),Ot()]),p=Fo(),m=h?ni(p,h):new Map,f=Array.from(m.entries()).sort((_,S)=>_[0].localeCompare(S[0])),y=(h==null?void 0:h.length)||0,g=(h==null?void 0:h.filter(_=>_.entityType==="visual").length)||0,x=(h==null?void 0:h.filter(_=>_.entityType==="library").length)||0,v=h?ri(p,h):[],b=v.length,C=(h==null?void 0:h.filter(_=>(_.analyses??[]).filter(S=>S.scenarios&&S.scenarios.length>0).length>0).length)||0,N=(h==null?void 0:h.reduce((_,S)=>{var F,q,J;const T=((J=(q=(F=S.analyses)==null?void 0:F[0])==null?void 0:q.scenarios)==null?void 0:J.length)||0;return _+T},0))||0,k=(h==null?void 0:h.reduce((_,S)=>{var q,J;const F=(((J=(q=S.analyses)==null?void 0:q[0])==null?void 0:J.scenarios)||[]).filter(U=>{var Y,z;return(z=(Y=U.metadata)==null?void 0:Y.screenshotPaths)==null?void 0:z[0]}).length;return _+F},0))||0,w=[];h==null||h.forEach(_=>{var T;const S=(T=_.analyses)==null?void 0:T[0];S!=null&&S.scenarios&&S.scenarios.filter(q=>{var J;return!((J=q.metadata)!=null&&J.sameAsDefault)}).forEach(q=>{var U,Y;const J=(Y=(U=q.metadata)==null?void 0:U.screenshotPaths)==null?void 0:Y[0];J&&w.push({entitySha:_.sha,entityName:_.name,scenarioId:q.id,scenarioName:q.name,screenshotPath:J,createdAt:S.createdAt||""})})}),w.sort((_,S)=>new Date(S.createdAt).getTime()-new Date(_.createdAt).getTime());const A=w.slice(0,16),M=(h==null?void 0:h.filter(_=>_.entityType==="visual").filter(_=>{var F,q;const S=(F=_.analyses)==null?void 0:F[0];return!((q=S==null?void 0:S.scenarios)==null?void 0:q.some(J=>{var U,Y;return(Y=(U=J.metadata)==null?void 0:U.screenshotPaths)==null?void 0:Y[0]}))}).slice(0,8))||[],I=(s=u==null?void 0:u.metadata)==null?void 0:s.currentRun,D=((o=I==null?void 0:I.currentEntityShas)==null?void 0:o.length)||0,L=d.jobs.length||0;return B({stats:{totalEntities:y,visualEntities:g,libraryEntities:x,uncommittedEntities:b,entitiesWithAnalyses:C,totalScenarios:N,capturedScreenshots:k,currentlyAnalyzing:D,filesOnQueue:L},uncommittedFiles:f,uncommittedEntitiesList:v,recentSimulations:A,visualEntitiesForSimulation:M,projectSlug:i,queueState:d,currentCommit:u})}catch(i){return console.error("Failed to load dashboard data:",i),B({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 Eg=De(function(){var Y,z;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=Be(),h=Ae(),u=ot(),{showToast:p}=ta();Xe({source:"dashboard"});const[m,f]=P(new Set),[y,g]=P(null),[x,v]=P(!1),[b,C]=P(!1),{lastLine:N,isCompleted:k}=gt(i,!!y),{simulatingEntity:w,scenarios:A,scenarioStatuses:M,allScenariosCaptured:I}=re(()=>{var j,R;const $={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return $;const E=o==null?void 0:o.find(G=>G.sha===y);if(!E)return $;const W=(j=E.analyses)==null?void 0:j[0],H=(W==null?void 0:W.scenarios)||[],V=((R=W==null?void 0:W.status)==null?void 0:R.scenarios)||[],ae=V.filter(G=>G.screenshotFinishedAt).length,O=H.length>0&&ae===H.length;return{simulatingEntity:E,scenarios:H,scenarioStatuses:V,allScenariosCaptured:O}},[y,o]);ee(()=>{(k||I)&&g(null)},[k,I]);const D=(Y=d==null?void 0:d.metadata)==null?void 0:Y.currentRun,L=new Set((D==null?void 0:D.currentEntityShas)||[]),_=new Set(c.jobs.flatMap($=>$.entityShas||[])),S=new Set(((z=c.currentlyExecuting)==null?void 0:z.entityShas)||[]),T=a.filter($=>$.entityType==="visual"||$.entityType==="library"),F=T.filter($=>!L.has($.sha)&&!_.has($.sha)&&!S.has($.sha)),q=()=>{if(F.length===0){p("All entities are already queued or analyzing","info",3e3);return}const $=F.map(E=>E.sha);C(!0),p(`Starting analysis for ${F.length} entities...`,"info",3e3),h.submit({entityShas:$.join(",")},{method:"post",action:"/api/analyze"})};ee(()=>{if(h.state==="idle"&&h.data){const $=h.data;$.success?(console.log("[Analyze All] Success:",$.message),p(`Analysis started for ${$.entityCount} entities in ${$.fileCount} files. Watch the logs for progress.`,"success",6e3),C(!1)):$.error&&(console.error("[Analyze All] Error:",$.error),p(`Error: ${$.error}`,"error",8e3),C(!1))}},[h.state,h.data,p]);const J=$=>{f(E=>{const W=new Set(E);return W.has($)?W.delete($):W.add($),W})},U=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children: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:[n("img",{src:Cg,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,$=>$.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:U.map(($,E)=>n(se,{to:$.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 ${$.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:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:$.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[$.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:$.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:`${$.color}15`},children:[$.iconType==="folder"&&n(tl,{size:20,style:{color:$.color}}),$.iconType==="check"&&n(Jr,{size:20,style:{color:$.color}}),$.iconType==="image"&&n(tn,{size:20,style:{color:$.color}}),$.iconType==="code-xml"&&n(nl,{size:20,style:{color:$.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:$.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:$.color},children:"View All →"})]})]})},E))}),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:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),T.length>0&&n("button",{onClick:q,disabled:h.state!=="idle"||b||F.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:$=>$.currentTarget.style.backgroundColor="#004560",onMouseLeave:$=>$.currentTarget.style.backgroundColor="#005C75",children:h.state!=="idle"||b?"Starting analysis...":F.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([$,E])=>{const W=m.has($),H=E.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>J($),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:W?"▼":"▶"}),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:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:$}),l("span",{className:"text-xs text-gray-500",children:[H.length," entit",H.length!==1?"ies":"y"]})]})]})}),W&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:H.length>0?H.map(V=>{const ae=L.has(V.sha),O=_.has(V.sha)||S.has(V.sha);return l(se,{to:`/entity/${V.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:j=>j.currentTarget.style.borderColor="#005C75",onMouseLeave:j=>j.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:V.entityType==="visual"?"#8B5CF615":V.entityType==="library"?"#6366F1":"#EC4899"},children:[V.entityType==="visual"&&n(tn,{size:16,style:{color:"#8B5CF6"}}),V.entityType==="library"&&n(zs,{size:16,className:"text-white"}),V.entityType==="other"&&n(rl,{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:[n("div",{className:"font-semibold text-gray-900 text-sm",children:V.name}),V.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),V.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),V.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),V.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:V.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:[n(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ae&&O&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ae&&!O&&n("button",{onClick:j=>{j.preventDefault(),j.stopPropagation(),p(`Starting analysis for ${V.name}...`,"info",3e3),h.submit({entityShas:V.sha},{method:"post",action:"/api/analyze"})},disabled:h.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:j=>j.currentTarget.style.backgroundColor="#004560",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},V.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},$)})}):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:[n("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:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(wg,{recentSimulations:s}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[w&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Ve,{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 ",w.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:w.filePath})]})]})}),I?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):N?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ze,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:N,children:N}),i&&n("button",{onClick:()=>v(!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"})]}):h.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:[n(Ze,{size:18,className:"animate-spin shrink-0"}),n("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:[n(Ze,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map(($,E)=>{var R,G,te;const W=(R=w==null?void 0:w.analyses)==null?void 0:R[0],H=dr($,W==null?void 0:W.status,void 0,y||void 0,void 0),V=(te=(G=$.metadata)==null?void 0:G.screenshotPaths)==null?void 0:te[0],ae=H.isCaptured,O=H.status==="capturing"||H.status==="starting",j=H.hasError;return ae?n(se,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(Ye,{screenshotPath:V,alt:$.name,title:$.name,className:"max-w-full max-h-full object-contain object-center"})},E):j?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:H.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},E):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${O?"Capturing":"Pending"} ${$.name}...`,children:n("span",{className:O?"animate-pulse":"text-gray-400",children:O?"⋯":"⏹️"})},E)})})]})]})]}),x&&i&&n(pt,{projectSlug:i,onClose:()=>v(!1)})]})})}),Ag=Object.freeze(Object.defineProperty({__proto__:null,default:Eg,loader:Sg,meta:Ng},Symbol.toStringTag,{value:"Module"}));function ai({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Rl,{remarkPlugins:[Dl],components:{h1:({children:a})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:a}),h2:({children:a})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:a}),h3:({children:a})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:a}),p:({children:a})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:a}),ul:({children:a})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),ol:({children:a})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),li:({children:a})=>n("li",{className:"leading-relaxed",children:a}),code:({children:a,className:s})=>(s==null?void 0:s.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:a})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:a}),pre:({children:a})=>n(he,{children:a}),strong:({children:a})=>n("strong",{className:"font-semibold text-gray-900",children:a}),blockquote:({children:a})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:a}),table:({children:a})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:a})}),thead:({children:a})=>n("thead",{className:"bg-gray-50",children:a}),th:({children:a})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:a}),td:({children:a})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:a}),a:({children:a,href:s})=>n("a",{href:s,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:a})},children:r})}function si(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const a=r.filePath.split("/");a.pop();let s=t,o="";for(const i of a)o=o?`${o}/${i}`:i,s.children.has(i)||s.children.set(i,{name:i,path:o,memories:[],children:new Map}),s=s.children.get(i);a.length===0?t.memories.push(r):s.memories.push(r)}return t}function oi(e){let t=e.memories.length;for(const r of e.children.values())t+=oi(r);return t}function mr(e,t){var a;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||t}function en(e){return Math.round(e/3.5)}function va(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),h=Math.floor(d/(1e3*60*60));return h<1?"Just now":h===1?"1h ago":`${h}h ago`}const s=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${s} ${o}`:`${s} ${o}, ${i}`}function kg({rule:e,onEdit:t,onDelete:r,onView:a,isReviewed:s,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:h,isFadingOut:u,showLeftBorder:p}){const[m,f]=P(!1),[y,g]=P(!1),x=re(()=>mr(e.body,e.filePath),[e.body,e.filePath]),v=en(e.body.length),b=m?"#3e3e3e":c?"#d97706":"#c7c7c7",C=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,N={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:C,style:N,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>a?a(e):f(!m),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(he,{children:[e.frontmatter.paths.slice(0,2).map((k,w)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:k},w)),e.frontmatter.paths.length>2&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:va(d)}),o&&n("button",{onClick:k=>{k.stopPropagation(),o(e.filePath,e.lastModified,s??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${s?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:s?"Mark as unreviewed":"Mark as reviewed",children:s&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&h&&l("button",{onClick:k=>{k.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(jn,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:k=>{k.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(al,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:k=>{k.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(sl,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&h&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.split(`
251
- `).map((k,w)=>{let A="";return k.startsWith("+")&&!k.startsWith("+++")?A="text-green-400":k.startsWith("-")&&!k.startsWith("---")?A="text-red-400":k.startsWith("@@")&&(A="text-cyan-400"),n("div",{className:A,children:k},w)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(Jo,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((k,w)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:k},w))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(ai,{content:e.body})})]})]})}function Pg(){return new Date().toISOString().split(".")[0]+"",`---
252
- paths:
253
- - '**/*.ts'
254
- ---
255
-
256
- ## Title
257
-
258
- Description here.
259
- `}function _g({rule:e,onSave:t,onCancel:r}){const[a,s]=P(e?`.claude/rules/${e.filePath}`:""),[o,i]=P((e==null?void 0:e.content)||Pg()),[c,d]=P(!!e),h=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(qr,{className:"w-5 h-5"})})]}),h&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(jn,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),n("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:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!h)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:a,onChange:u=>s(u.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(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:n(Rt,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${a}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${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 prompt",children:n(Rt,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:u=>i(u.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:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(a.replace(/^\.claude\/rules\//,""),o),disabled:!a.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Mg({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:a,onToggleFolder:s}){const o=re(()=>si(e),[e]),i=(h,u,p)=>{if(h.target.closest(".chevron-toggle")){p&&s(u||"root");return}const f=u||null;r(t===f?null:f),p&&!a.has(u||"root")&&s(u||"root")},c=h=>{r(t===h?null:h)},d=(h,u=0)=>{const p=a.has(h.path||"root"),m=oi(h),f=h.children.size>0,y=h.name==="root"?"(root)":h.name,g=h.memories.length>0||f,x=h.path||"",v=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,h.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),s(h.path||"root")},children:n(jt,{className:`w-3 h-3 text-gray-500 transition-transform ${p?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Bs,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[m," rules"]})]}),p&&l("div",{className:"relative",children:[(h.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(b=>{var N;const C=t===b.filePath;return n("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:()=>c(b.filePath),children:n("span",{className:"text-xs",children:(N=b.filePath.split("/").pop())==null?void 0:N.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(h.children.values()).sort((b,C)=>b.name.localeCompare(C.name)).map(b=>d(b,u+1))})]})]},h.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function Tg({memories:e,onEdit:t,onDelete:r,expandedFolders:a,onToggleFolder:s,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[h,u]=P({});ee(()=>{u({})},[o]);const p=re(()=>({...o,...h}),[o,h]),m=re(()=>si(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?c(g):i(g,x)},y=(g,x=0)=>{const v=a.has(g.path||"root"),b=g.children.size>0,C=g.name==="root"?"root":g.name,N=g.memories.length>0||b;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:()=>N&&s(g.path||"root"),children:[N&&n(jt,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!N&&n("div",{className:"w-4"}),n(Bs,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:C})]}),v&&l("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(k=>n(kg,{rule:k,onEdit:t,onDelete:r,onView:d,isReviewed:p[k.filePath]??!1,onToggleReviewed:f},k.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((k,w)=>k.name.localeCompare(w.name)).map(k=>y(k,x+1))})]})]},g.path||"root")};return n("div",{children:y(m)})}function jg({memories:e,reviewedStatus:t,onViewRule:r}){const[a,s]=P("unreviewed"),[o,i]=P(new Map),c=Ne(t),d=Ne([]);ee(()=>()=>{d.current.forEach(clearTimeout)},[]),ee(()=>{const m=c.current,f=[];for(const[y,g]of Object.entries(t))g&&!m[y]&&f.push(y);c.current=t,f.length!==0&&(i(y=>{const g=new Map(y);return f.forEach(x=>g.set(x,"approved")),g}),d.current.push(setTimeout(()=>{i(y=>{const g=new Map(y);return f.forEach(x=>g.set(x,"fading")),g})},1500)),d.current.push(setTimeout(()=>{i(y=>{const g=new Map(y);return f.forEach(x=>g.delete(x)),g})},2500)))},[t]);const h=re(()=>[...e].sort((m,f)=>new Date(f.lastModified).getTime()-new Date(m.lastModified).getTime()),[e]),u=re(()=>h.filter(m=>!t[m.filePath]).length,[h,t]),p=re(()=>a==="unreviewed"?h.filter(m=>!t[m.filePath]||o.has(m.filePath)):h,[h,a,t,o]);return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>s("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",u,")"]})]}),l("button",{onClick:()=>s("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",h.length,")"]})]})]}),l("div",{className:"grid grid-cols-[1fr_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center",children:"Changed At"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n(Lr,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto",children:p.slice(0,8).map(m=>{const f=t[m.filePath]??!1,y=o.get(m.filePath),g=mr(m.body,m.filePath);return n("div",{className:`border-b border-gray-50 transition-all ${y==="fading"?"duration-1000":"duration-300"}`,style:{opacity:y==="fading"?0:1},children:l("div",{className:`grid grid-cols-[1fr_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${y==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(m),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:g})}),n("span",{className:"text-xs text-gray-500 text-center",children:va(m.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${f?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:f&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},m.filePath)})}),p.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"}),p.length>0&&p.length<6&&n("div",{className:"h-[60px] flex-shrink-0",style:{backgroundColor:"#F0F0F0"}})]})}function Ig({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:a}){const[s,o]=P("unreviewed"),[i,c]=P(null),[d,h]=P(""),[u,p]=P(0),[m,f]=P(!1),[y,g]=P(null),x=Ne(null),v=Ne(null),[b,C]=P({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[N,k]=P(!0);ee(()=>{(async()=>{k(!0);try{const F=await(await fetch("/api/memory?action=audit")).json();C({topPaths:F.topPaths||[],totalFilesWithCoverage:F.totalFilesWithCoverage||0,allSourceFiles:F.allSourceFiles||[]})}catch(T){console.error("Failed to load audit data:",T)}finally{k(!1)}})()},[e]);const w=re(()=>s==="all"?b.topPaths:b.topPaths.filter(S=>S.matchingRules.some(T=>!t[T.filePath])),[b.topPaths,s,t]);re(()=>b.topPaths.filter(S=>S.matchingRules.some(T=>!t[T.filePath])).length,[b.topPaths,t]);const A=S=>S.split("/").pop()||S,M=re(()=>{const S=new Map;for(const T of b.topPaths)S.set(T.filePath,T);return S},[b.topPaths]),I=re(()=>{if(!d.trim())return[];const S=d.toLowerCase(),T=[],F=[];for(const q of b.allSourceFiles){const J=q.toLowerCase();if(!J.includes(S))continue;const U=M.get(q)||{filePath:q,matchingRules:[],totalTextLength:0};J.startsWith(S)?T.push(U):F.push(U)}return T.sort((q,J)=>q.filePath.localeCompare(J.filePath)),F.sort((q,J)=>q.filePath.localeCompare(J.filePath)),[...T,...F].slice(0,8)},[d,b.allSourceFiles,M]),D=oe(S=>{var T;g(S),c(S.filePath),h(S.filePath),f(!1),(T=x.current)==null||T.blur()},[]),L=oe(()=>{var S;h(""),g(null),c(null),(S=x.current)==null||S.focus()},[]),_=oe(S=>{var T;!m||I.length===0||(S.key==="ArrowDown"?(S.preventDefault(),p(F=>Math.min(F+1,I.length-1))):S.key==="ArrowUp"?(S.preventDefault(),p(F=>Math.max(F-1,0))):S.key==="Enter"?(S.preventDefault(),D(I[u])):S.key==="Escape"&&(f(!1),(T=x.current)==null||T.blur()))},[m,I,u,D]);return ee(()=>{p(0)},[I]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(ln,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:x,type:"text",value:d,onChange:S=>{h(S.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:_,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:S=>{S.preventDefault(),L()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),m&&I.length>0&&n("div",{ref:v,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:I.map((S,T)=>l("div",{onMouseDown:F=>{F.preventDefault(),D(S)},onMouseEnter:()=>p(T),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${T===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(In,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:S.filePath,children:(()=>{const F=S.filePath.toLowerCase().indexOf(d.toLowerCase());if(F===-1)return S.filePath;const q=S.filePath.slice(0,F),J=S.filePath.slice(F,F+d.length),U=S.filePath.slice(F+d.length);return l(he,{children:[q,n("span",{className:"font-semibold text-[#005C75]",children:J}),U]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[S.matchingRules.length," rule",S.matchingRules.length!==1?"s":""]})]},S.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400,color:s==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400,color:s==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n(Lr,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n(Lr,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),N&&n("div",{className:"px-5 py-6",children:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!N&&(w.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...w.filter(T=>T.filePath!==y.filePath)].slice(0,8):w.slice(0,8)).map((S,T)=>{const F=S.matchingRules.length,q=S.matchingRules.filter(E=>!t[E.filePath]),J=q.length,U=q.reduce((E,W)=>E+W.bodyLength,0),Y=J>0,z=i===S.filePath,$=(y==null?void 0:y.filePath)===S.filePath;return l("div",{children:[l("div",{onClick:()=>c(z?null:S.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${$?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[z?n(st,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(jt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(In,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:S.filePath,children:$?S.filePath:A(S.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:Y?"font-semibold text-[#1A5276]":"text-gray-400",children:J}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:F})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:Y?"font-semibold text-[#1A5276]":"text-gray-400",children:en(U).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:en(S.totalTextLength).toLocaleString()})]})]}),z&&n("div",{className:"bg-gray-50 border-b border-gray-100",children:S.matchingRules.map(E=>{const W=r.find(V=>V.filePath===E.filePath),H=t[E.filePath]??!1;return l("div",{onClick:V=>{V.stopPropagation(),W&&a(W)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Gr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:W?mr(W.body,W.filePath):E.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[en(E.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${H?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:H&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},E.filePath)})})]},S.filePath)})}),!N&&w.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:s==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"})]})}function $g({rule:e,changeInfo:t,isReviewed:r,onApprove:a,onEdit:s,onDelete:o,onClose:i}){const c=mr(e.body,e.filePath),d=en(e.body.length),h=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[p,m]=P(!1);return ee(()=>{const f=y=>{y.key==="Escape"&&i()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:l("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:f=>f.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(he,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:va(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),h&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:h})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n("button",{onClick:()=>{navigator.clipboard.writeText(u),m(!0),setTimeout(()=>m(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors",title:"Copy file path",children:p?n(kt,{className:"w-3 h-3 text-green-500"}):n(Rt,{className:"w-3 h-3"})})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick:a,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(kt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:s,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(qr,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((f,y)=>{const g=f.split("/"),x=g.pop()||f,v=g.length>0?g.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(In,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[v&&n("span",{className:"text-gray-500",children:v}),n("span",{className:"font-bold text-gray-900",children:x})]})]},y)})})]}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(ai,{content:e.body})})]})]})})}function Rg(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function Dg(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function Lg(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Ds,{value:"/codeyam-memory"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Confirm or refine the confusion patterns Claude discovers in your git history"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"4"}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Review generated rules here, in the dashboard"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"Come back to this page to review, edit, and approve the rules Claude creates."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Ds,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in your terminal to get started"})]})]})})}function Ds({value:e}){const[t,r]=P(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(kt,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function kn({label:e,count:t,icon:r,bgColor:a,iconBgColor:s,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:a,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:s},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function Fg({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:a,reviewCounts:s}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(Rg,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:a,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Kr,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(kn,{label:"Total Rules",count:s.total,icon:n(Dg,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(kn,{label:"Unreviewed",count:s.unreviewed,icon:n(ol,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(kn,{label:"Reviewed",count:s.reviewed,icon:n(kt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(kn,{label:"Stale",count:s.stale,icon:n(Ys,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function Og({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(qr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Kr,{className:"w-4 h-4"}),"New Rule"]})})]})})}function zg({rule:e,onConfirm:t,onCancel:r}){return n("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:[n("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"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Yg=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function Bg({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?B({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?B({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):B({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),B({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Ug=De(function(){const{memories:t,reviewedStatus:r,memoryInitialized:a,error:s}=Be(),o=Ae(),i=ot(),[c,d]=P(""),[h,u]=P(null),[p,m]=P(new Set(["root"])),[f,y]=P(null),[g,x]=P(!1),[v,b]=P(null),[C,N]=P(0),[k,w]=P(!1),[A,M]=P(null),[I,D]=P(null),[L,_]=P({}),S=O=>{m(j=>{const R=new Set(j);return R.has(O)?R.delete(O):R.add(O),R})};Xe({source:"memory-page"});const T=re(()=>({...r,...L}),[r,L]),F=Ne(o.state);ee(()=>{const O=F.current==="loading"||F.current==="submitting",j=o.state==="idle";O&&j&&o.data&&(i.revalidate(),y(null),x(!1),N(R=>R+1)),F.current=o.state},[o.state,o.data,i]),ee(()=>{_(O=>{const j={};for(const[R,G]of Object.entries(O))r[R]!==G&&(j[R]=G);return Object.keys(j).length===Object.keys(O).length?O:j})},[r]);const q=(O,j)=>{_(R=>({...R,[O]:!0})),o.submit({action:"mark-reviewed",filePath:O,lastModified:j},{method:"POST",action:"/api/memory",encType:"application/json"})},J=O=>{_(j=>({...j,[O]:!1})),o.submit({action:"mark-unreviewed",filePath:O},{method:"POST",action:"/api/memory",encType:"application/json"})},U=(O,j)=>{M(O),D(j??null)},Y=re(()=>{let O=t;if(c.trim()){const j=c.toLowerCase();O=O.filter(R=>{var te;return(((te=R.filePath.split("/").pop())==null?void 0:te.replace(".md",""))||"").toLowerCase().includes(j)||R.body.toLowerCase().includes(j)})}return O},[t,c]),z=re(()=>h?Y.some(j=>j.filePath===h)?Y.filter(j=>j.filePath===h):Y.filter(j=>j.filePath.startsWith(h+"/")||j.filePath===h):Y,[Y,h]),$=(O,j)=>{const R=f?"update":"create";o.submit({action:R,filePath:O,content:j},{method:"POST",action:"/api/memory",encType:"application/json"})},E=O=>{o.submit({action:"delete",filePath:O.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},W=re(()=>{const O=t.filter(j=>T[j.filePath]).length;return{total:t.length,reviewed:O,unreviewed:t.length-O,stale:0}},[t,T]),H=re(()=>{const O=new Set(["root"]);for(const j of Y){const R=j.filePath.split("/");R.pop();let G="";for(const te of R)G=G?`${G}/${te}`:te,O.add(G)}return O},[Y]),V=H.size===p.size&&[...H].every(O=>p.has(O)),ae=()=>{m(V?new Set(["root"]):new Set(H))};return s?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:s})]})}):a?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(Fg,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>w(!0),reviewCounts:W}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:O=>O.stopPropagation(),children:n(_g,{rule:f,onSave:$,onCancel:()=>{x(!1),y(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(jg,{memories:Y,reviewedStatus:T,onViewRule:U}),n(Ig,{onEditRule:y,onDeleteRule:b,refreshKey:C,reviewedStatus:T,onMarkReviewed:q,onMarkUnreviewed:J,memories:t,onViewRule:U})]}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:H.size>1&&n("button",{onClick:ae,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:V?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Mg,{memories:Y,selectedPath:h,onSelectPath:u,expandedFolders:p,onToggleFolder:S})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(il,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),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:[n(Kr,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[h&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:h||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Tg,{memories:z,onEdit:y,onDelete:b,expandedFolders:p,onToggleFolder:S,reviewedStatus:T,onMarkReviewed:q,onMarkUnreviewed:J,onViewRule:U})]})})]}),n("div",{className:"mt-8 mb-8",children:n(se,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),A&&!f&&(()=>{const O=t.find(j=>j.filePath===A.filePath)??A;return n($g,{rule:O,changeInfo:I??void 0,isReviewed:T[O.filePath]??!1,onApprove:()=>{T[O.filePath]??!1?J(O.filePath):q(O.filePath,O.lastModified),M(null)},onEdit:()=>{y(O)},onDelete:()=>{b(O),M(null)},onClose:()=>M(null)})})(),k&&n(Og,{onClose:()=>w(!1),onCreateNew:()=>{w(!1),x(!0)}}),v&&n(zg,{rule:v,onConfirm:E,onCancel:()=>b(null)})]})}):n(Lg,{})}),Wg=Object.freeze(Object.defineProperty({__proto__:null,default:Ug,loader:Bg,meta:Yg},Symbol.toStringTag,{value:"Module"}));function Dr(e){return`${e.filePath||""}::${e.name}`}function ii(e,t){const r=Ae(),{showToast:a}=ta(),[s,o]=P(new Map);ee(()=>{if(r.state==="idle"&&r.data){const m=r.data;m!=null&&m.error&&a(`Error: ${m.error}`,"error",6e3)}},[r.state,r.data,a]),ee(()=>{var f;if(s.size===0)return;const m=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{s.forEach((v,b)=>{v===x&&m.add(b)})})}),e==null||e.forEach(y=>{s.forEach((g,x)=>{g===y&&m.add(x)})}),m.size>0&&o(y=>{const g=new Map(y);return m.forEach(x=>g.delete(x)),g})},[t,e,s]);const i=oe(m=>{console.log("Generate analysis clicked for entity:",m.sha,m.name);const f=Dr(m);o(g=>new Map(g).set(f,m.sha));const y=new FormData;y.append("entitySha",m.sha),y.append("filePath",m.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=oe(m=>{const f=m.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(Dr(b),b.sha)),v});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=oe(m=>(e==null?void 0:e.includes(m))??!1,[e]),h=oe(m=>{const f=Dr(m);return s.has(f)},[s]),u=oe(m=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(m)}))??!1},[t]),p=re(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:p}}function wa({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:s=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children: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:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("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:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:s,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:s?o:"Analyze all entities",children:o})})]})]})]})})}function Hg({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},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(t==="full"){const o=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const s=r[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${s.bgColor}`,title:e,children:s.label}),s.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Ca({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:p=!1,isUncommitted:m=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{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:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Zs,{filePath:e}),a&&n(Hg,{status:typeof a=="string"?a:a.status,variant:"full"}),m&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(m||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:s}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Go(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Na({entities:e,maxPreviews:t=3}){var a,s,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const h=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const u=h.find(p=>{var m,f;return((m=p.metadata)==null?void 0:m.executionResult)||((f=p.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(p=>{var m,f;return(f=(m=p.metadata)==null?void 0:m.screenshotPaths)==null?void 0:f[0]});if(u){const p=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],m=!!((c=u.metadata)!=null&&c.error);p&&r.push({type:"screenshot",screenshot:p,hasError:m,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(he,{children:r.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(se,{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:[n(Ye,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Tn,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(Ho,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function Sa({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,p;const s=t||r?[{entityShas:[e.sha]}]:[],o=qe(e,s,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((p=(u=e.analyses)==null?void 0:u[0])==null?void 0:p.scenarios)||[]).filter(m=>{var f,y;return(y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(se,{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:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Ve,{type:"type"})})}):n(Ve,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(ma,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?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:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),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&&n("button",{onClick:m=>{m.preventDefault(),m.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"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((m,f)=>{var g,x;const y=(x=(g=m.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(se,{to:`/entity/${e.sha}?scenario=${m.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:v=>v.stopPropagation(),children:n(Ye,{screenshotPath:y,alt:m.name,className:"max-w-full max-h-full object-contain object-center"})},m.id):null})})]})}function Vg({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:p,totalEntitiesCount:m,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=on(),[b,C]=P(new Set),[N,k]=P(""),[w,A]=P(!1),[M,I]=P("all"),[D,L]=P("desc"),_=o||"all",S=re(()=>{let E=e;return _!=="all"&&(E=E.filter(W=>W.entityType===_)),s==="analyzed"&&(E=E.filter(W=>W.analyses&&W.analyses.length>0)),E},[e,_,s]),T=re(()=>{const E=new Map,W=new Map,H=new Map;S.forEach(j=>{var te,ce;const R=`${j.filePath}::${j.name}`,G=W.get(R);if(!G)W.set(R,j),H.set(R,[]);else{const pe=((te=G.metadata)==null?void 0:te.editedAt)||G.createdAt||"",me=((ce=j.metadata)==null?void 0:ce.editedAt)||j.createdAt||"";let be=!1;if(me>pe)be=!0;else if(me===pe){const Ce=G.createdAt||"";be=(j.createdAt||"")>Ce}be?(H.get(R).push(G),W.set(R,j)):H.get(R).push(j)}}),W.forEach((j,R)=>{var te;if(!(j.analyses&&j.analyses.length>0)&&((te=j.metadata)!=null&&te.previousVersionWithAnalyses)){const pe=(H.get(R)||[]).find(me=>{var be;return me.sha===((be=j.metadata)==null?void 0:be.previousVersionWithAnalyses)});pe&&pe.analyses&&pe.analyses.length>0&&(j.analyses=pe.analyses)}}),Array.from(W.values()).sort((j,R)=>{var ce,pe,me,be;const G=!((ce=j.metadata)!=null&&ce.notExported)&&!((pe=j.metadata)!=null&&pe.namedExport),te=!((me=R.metadata)!=null&&me.notExported)&&!((be=R.metadata)!=null&&be.namedExport);return G&&!te?-1:!G&&te?1:0}).forEach(j=>{var pe,me,be,Ce,Ee;const R=j.filePath??"No File Path";E.has(R)||E.set(R,{filePath:R,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=E.get(R);G.entities.push(j),G.totalCount++,(pe=j.metadata)!=null&&pe.isUncommitted&&G.uncommittedCount++;const te=((Ce=(be=(me=j.analyses)==null?void 0:me[0])==null?void 0:be.scenarios)==null?void 0:Ce.length)||0;G.simulationCount+=te;const ce=((Ee=j.metadata)==null?void 0:Ee.editedAt)||j.updatedAt;ce&&(!G.lastUpdated||new Date(ce)>new Date(G.lastUpdated))&&(G.lastUpdated=ce)});const V=(i==null?void 0:i.jobs)||[],ae=j=>{const R=`${j.filePath||""}::${j.name}`;return(d==null?void 0:d.includes(R))||!1};E.forEach(j=>{const R=j.entities.map(G=>ae(G)?"queued":qe(G,V));R.includes("analyzing")||R.includes("queued")?j.state="analyzing":R.includes("incomplete")?j.state="incomplete":R.includes("out-of-date")?j.state="out-of-date":R.includes("not-analyzed")?j.state="not-analyzed":j.state="up-to-date"}),E.forEach(j=>{var R,G,te,ce,pe;for(const me of j.entities){if(j.previewScreenshots.length+j.previewLibraryScenarios.length>=3)break;const Ce=((G=(R=me.analyses)==null?void 0:R[0])==null?void 0:G.scenarios)||[];if(me.entityType==="library"){const Ee=Ce.find(Se=>{var Pe,Te;return((Pe=Se.metadata)==null?void 0:Pe.executionResult)||((Te=Se.metadata)==null?void 0:Te.error)});Ee&&j.previewLibraryScenarios.push({scenario:Ee,entitySha:me.sha})}else{const Ee=Ce.find(Se=>{var Pe,Te;return(Te=(Pe=Se.metadata)==null?void 0:Pe.screenshotPaths)==null?void 0:Te[0]});if(Ee){const Se=(ce=(te=Ee.metadata)==null?void 0:te.screenshotPaths)==null?void 0:ce[0],Pe=!!((pe=Ee.metadata)!=null&&pe.error);Se&&!j.previewScreenshots.includes(Se)&&(j.previewScreenshots.push(Se),j.previewScreenshotErrors.push(Pe))}}}});const O=Array.from(E.values());return O.sort((j,R)=>{if(s==="analyzed"){const ce=Math.max(...j.entities.filter(me=>{var be,Ce;return(Ce=(be=me.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(me=>new Date(me.analyses[0].createdAt).getTime()),0),pe=Math.max(...R.entities.filter(me=>{var be,Ce;return(Ce=(be=me.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(me=>new Date(me.analyses[0].createdAt).getTime()),0);return D==="desc"?pe-ce:ce-pe}if(j.uncommittedCount>0&&R.uncommittedCount===0)return-1;if(j.uncommittedCount===0&&R.uncommittedCount>0)return 1;const G=j.lastUpdated?new Date(j.lastUpdated).getTime():0,te=R.lastUpdated?new Date(R.lastUpdated).getTime():0;return D==="desc"?te-G:G-te}),O},[S,s,D,i,d]),F=re(()=>{let E=T;if(M!=="all"&&(E=E.filter(W=>W.state===M)),N.trim()){const W=N.toLowerCase();E=E.filter(H=>H.filePath.toLowerCase().includes(W))}return E},[T,N,M]),q=(t-1)*r,J=q+r,U=F.slice(q,J),Y=Math.ceil(F.length/r),z=E=>{C(W=>{const H=new Set(W);return H.has(E)?H.delete(E):H.add(E),H})},$=()=>{L(E=>E==="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:[n("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:_,onChange:E=>{const W=E.target.value,H=new URLSearchParams(x);W==="all"?H.delete("entityType"):H.set("entityType",W),H.set("page","1"),v(H)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(st,{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:M,onChange:E=>I(E.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(st,{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:[n(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:N,onChange:E=>k(E.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&&m!==void 0&&f!==void 0&&n("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:[n("span",{style:{color:"#000000"},children:F.length})," ",F.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:F.reduce((E,W)=>E+W.totalCount,0)})," ",F.reduce((E,W)=>E+W.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?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:[F.filter(E=>E.uncommittedCount>0).length," ","uncommitted"," ",F.filter(E=>E.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):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"]})]}),U.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{C(new Set(U.map(E=>E.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:[n(Us,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{C(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:[n(Ws,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(wa,{showActions:!0,sortOrder:D,onSortChange:$}),n("div",{className:"flex flex-col gap-[3px]",children:U.map(E=>{const W=b.has(E.filePath),V=E.entities.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&(qe(R,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(R,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(R,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ae=R=>{var G;return((G=a==null?void 0:a.currentEntityShas)==null?void 0:G.includes(R))||!1},O=R=>{var G;return c!=null&&c(R)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(te=>{var ce;return(ce=te.entityShas)==null?void 0:ce.includes(R.sha)}))||!1},j=R=>{h==null||h(R)};return n(Ca,{filePath:E.filePath,isExpanded:W,onToggle:()=>z(E.filePath),simulationPreviews:n(Na,{entities:E.entities,maxPreviews:1}),entityCount:E.totalCount,state:E.state,lastModified:E.lastUpdated,uncommittedCount:E.uncommittedCount,isUncommitted:E.uncommittedCount>0,actionButton:V?n("button",{onClick:R=>{R.stopPropagation();const G=E.entities.filter(te=>(te.entityType==="visual"||te.entityType==="library")&&(qe(te,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(te,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(te,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(G)},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:E.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:E.entities.sort((R,G)=>{var be,Ce,Ee,Se;const te=!((be=R.metadata)!=null&&be.notExported)&&!((Ce=R.metadata)!=null&&Ce.namedExport),ce=!((Ee=G.metadata)!=null&&Ee.notExported)&&!((Se=G.metadata)!=null&&Se.namedExport);if(te&&!ce)return-1;if(!te&&ce)return 1;const pe=R.entityType==="visual"||R.entityType==="library",me=G.entityType==="visual"||G.entityType==="library";return pe&&!me?-1:!pe&&me?1:R.name.localeCompare(G.name)}).map(R=>n(Sa,{entity:R,isActivelyAnalyzing:ae(R.sha),isQueued:O(R),onGenerateSimulation:j},R.sha))},E.filePath)})}),Y>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",Y]}),t<Y&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Jg=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Gg({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),s=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([un(),Ot()]);return B({entities:d,currentCommit:h,page:a,filter:s,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),B({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const qg=De(function(){var N,k,w;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i,error:c}=Be();ot();const[d,h]=on(),[u,p]=P(!1);Xe({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=ii((k=(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun)==null?void 0:k.currentEntityShas,i),x=t||[],v=re(()=>{const A=new Set([]);for(const M of x)A.add(M.filePath??"No File Path");return Array.from(A)},[x]),b=re(()=>{let A=x;return u&&(A=A.filter(M=>{var I;return(I=M.metadata)==null?void 0:I.isUncommitted})),A.sort((M,I)=>{var D,L,_,S,T,F;return(D=M.metadata)!=null&&D.isUncommitted&&!((L=I.metadata)!=null&&L.isUncommitted)?-1:!((_=M.metadata)!=null&&_.isUncommitted)&&((S=I.metadata)!=null&&S.isUncommitted)?1:new Date(((T=I.metadata)==null?void 0:T.editedAt)||0).getTime()-new Date(((F=M.metadata)==null?void 0:F.editedAt)||0).getTime()})},[x,u]),C=re(()=>{var M;const A=new Set([]);for(const I of x)(M=I.metadata)!=null&&M.isUncommitted&&A.add(I.filePath??"No File Path");return Array.from(A)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("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"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Vg,{entities:b,page:a,itemsPerPage:50,currentRun:(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:C.length,showOnlyUncommitted:u,onToggleUncommitted:()=>p(!u)})]})})}),Kg=Object.freeze(Object.defineProperty({__proto__:null,default:qg,loader:Gg,meta:Jg},Symbol.toStringTag,{value:"Module"})),Qg=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function Zg({request:e}){var t;try{const r=await $e();if(!r)return B({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:a}=await Ie(r),s=ge()||process.cwd(),o=Bo(s)||"";let i="";try{const d=await nr();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const h=d.webapps.map(u=>u.framework).filter(Boolean);h.length>0&&(i=h.join(", "))}}catch{}const c=Wo(r);return B({labs:((t=a.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),B({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Xg({request:e}){try{const t=await e.formData(),r=t.get("feature"),a=t.get("enabled")==="true";if(!r)return B({success:!1,error:"Missing feature name"},{status:400});const s=await $e();return s?(r==="clearAccess"?await On({projectSlug:s,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await On({projectSlug:s,metadataUpdate:{labs:{[r]:a}}}),B({success:!0,error:null})):B({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),B({success:!1,error:"Failed to save labs configuration"},{status:500})}}const e0=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],Ls="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",t0=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function n0({onClose:e}){const t=Ne(null),r=Ne(0);return ee(()=>{const a=t.current;if(!a)return;const s=100,o=2e3,i=500;let c=null,d=!1;const h=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,p=a.scrollTop>s,m=u>o;p&&m&&(a.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return a.addEventListener("scroll",h,{passive:!0}),()=>{a.removeEventListener("scroll",h),c&&clearInterval(c)}},[]),l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:a=>{a.target===a.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{ref:t,className:"relative bg-white rounded-xl p-4 md:p-6 max-w-3xl w-full mx-4 max-h-[90vh] overflow-y-auto",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),l("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Ls}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Ls,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})}function r0({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:a}){var i,c;const s=(i=a.data)==null?void 0:i.error,o=(c=a.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(a.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||a.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:a.state==="submitting"?"Validating...":"Unlock"}),s&&n("p",{className:"text-red-600 text-sm mt-2",children:s}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const a0=De(function(){const{labs:t,unlockCode:r,error:a}=Be(),s=Ae(),o=Ae(),i=Ae(),[c,d]=P(""),[h,u]=P(!1),[p,m]=P(!1);Xe({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return a?n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:a})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:e0.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[h&&n(n0,{onClose:()=>u(!1)}),p&&n(r0,{onClose:()=>m(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:s}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>m(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:t0.map(y=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),s0=Object.freeze(Object.defineProperty({__proto__:null,action:Xg,default:a0,loader:Zg,meta:Qg},Symbol.toStringTag,{value:"Module"}));function o0(e,t,r){const[a,s]=P(()=>new Set),[o,i]=P(()=>new Set),c=Ne([]),d=Ne([]);return ee(()=>{(t.length!==c.current.length||t.some((g,x)=>g!==c.current[x]))&&(c.current=t,s(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),ee(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(v=>{const b=new Set(v);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function i0(e,t,r){const[a,s]=P(null),[o,i]=P(null),c=Ae();ee(()=>{var p,m;((p=c.data)==null?void 0:p.oldContent)!==void 0&&((m=c.data)==null?void 0:m.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=p=>{s({type:"file",path:p}),i(null);const m=new FormData;m.append("actionType","getDiff"),m.append("filePath",p),m.append("diffType","branch"),m.append("baseBranch",e),m.append("currentBranch",t||""),c.submit(m,{method:"post"})},h=(p,m)=>{s({type:"entity",path:p,entitySha:m}),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",t||""),f.append("entitySha",m),c.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function l0({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var h;const[o,i]=P(!1),[c,d]=P(!1);return ee(()=>{d(!0)},[]),n("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:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=a.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:c&&n(Ll,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:s,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 c0({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:p,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([C,{entities:N}])=>{const k=N.filter(w=>i(w.sha)||c(w)).map(w=>w.sha);return k.length>0?[{entityShas:k}]:[]}),v=C=>{const N=C.map(k=>qe(k,x));return N.includes("analyzing")||N.includes("queued")?"analyzing":N.includes("out-of-date")?"out-of-date":N.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=re(()=>[...e].sort((C,N)=>{const k=C[1].entities.reduce((I,D)=>{var _;const L=((_=D.metadata)==null?void 0:_.editedAt)||D.updatedAt;return L?I?new Date(L)>new Date(I)?L:I:L:I},null),w=N[1].entities.reduce((I,D)=>{var _;const L=((_=D.metadata)==null?void 0:_.editedAt)||D.updatedAt;return L?I?new Date(L)>new Date(I)?L:I:L:I},null);if(!k&&!w)return 0;if(!k)return 1;if(!w)return-1;const A=new Date(k).getTime(),M=new Date(w).getTime();return d==="desc"?M-A:A-M}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(wa,{showActions:!0,sortOrder:d,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([C,{status:N,entities:k,isUncommitted:w}])=>{const A=o.has(C),M=v(k),I=k.reduce((S,T)=>{var q;const F=((q=T.metadata)==null?void 0:q.editedAt)||T.updatedAt;return F?S?new Date(F)>new Date(S)?F:S:F:S},null),L=k.filter(S=>S.entityType==="visual"||S.entityType==="library").length===0;let _;return L?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="up-to-date"?_=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):M==="out-of-date"?_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>p(T))},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"}):M==="not-analyzed"&&(_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>p(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ca,{filePath:C,isExpanded:A,onToggle:()=>h(C),fileStatus:N,isUncommitted:w,simulationPreviews:n(Na,{entities:k,maxPreviews:1}),entityCount:k.length,state:M,lastModified:I,isNotAnalyzable:L,actionButton:_,children:k.sort((S,T)=>{const F=S.entityType==="visual"||S.entityType==="library",q=T.entityType==="visual"||T.entityType==="library";return F&&!q?-1:!F&&q?1:0}).map(S=>n(Sa,{entity:S,isActivelyAnalyzing:i(S.sha),isQueued:c(S),onGenerateSimulation:p},S.sha))},C)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function d0({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:p,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=re(()=>{const C=[];return e.forEach(([N,{editedEntities:k}])=>{const w=k.filter(A=>a(A.sha)||s(A)).map(A=>A.sha);w.length>0&&C.push({entityShas:w})}),C},[e,a,s]),v=re(()=>{const C=new Map;return e.forEach(([N,{editedEntities:k}])=>{const w=k.map(D=>qe(D,x));let A;w.includes("analyzing")||w.includes("queued")?A="analyzing":w.includes("out-of-date")?A="out-of-date":w.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const M=k.reduce((D,L)=>{var S;const _=((S=L.metadata)==null?void 0:S.editedAt)||L.updatedAt;return _&&(!D||new Date(_)>new Date(D))?_:D},null),I=k.filter(D=>D.entityType==="visual"||D.entityType==="library").length;C.set(N,{state:A,lastModified:M,analyzableCount:I})}),C},[e,x]),b=re(()=>[...e].sort((C,N)=>{const k=v.get(C[0]),w=v.get(N[0]),A=k==null?void 0:k.lastModified,M=w==null?void 0:w.lastModified;if(!A&&!M)return 0;if(!A)return 1;if(!M)return-1;const I=new Date(A).getTime(),D=new Date(M).getTime();return d==="desc"?D-I:I-D}),[e,v,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:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(wa,{showActions:!0,sortOrder:d,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([C,{status:N,editedEntities:k}])=>{const w=r.has(C),A=v.get(C),{state:M,lastModified:I,analyzableCount:D}=A,L=D===0;let _;return L?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="up-to-date"?_=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):M==="out-of-date"?_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>p(T))},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"}):M==="not-analyzed"&&(_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>p(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ca,{filePath:C,isExpanded:w,onToggle:()=>h(C),fileStatus:N,simulationPreviews:n(Na,{entities:k,maxPreviews:1}),entityCount:k.length,state:M,lastModified:I,isNotAnalyzable:L,isUncommitted:!0,actionButton:_,children:k.sort((S,T)=>{const F=S.entityType==="visual"||S.entityType==="library",q=T.entityType==="visual"||T.entityType==="library";return F&&!q?-1:!F&&q?1:0}).map(S=>n(Sa,{entity:S,isActivelyAnalyzing:a(S.sha),isQueued:s(S),onGenerateSimulation:p},S.sha))},C)})})]})}function u0({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const h0=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function m0({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),s=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),c=t.get("entitySha");let d;return s==="branch"?d=Pn(a,o,i):d=cm(a),B({...d,entitySha:c})}return B({error:"Unknown action"},{status:400})}async function p0({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),s=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[c,d,h]=await Promise.all([un(),Ot(),$e()]),u=Fo(),p=am(),m=sm(),f=om(),y=s||p,g=a||m;let x=[];return y&&y!==g&&(x=Oo(g,y)),B({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:p,defaultBranch:m,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),B({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 f0=De(function(){var ye,bt;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:h,projectSlug:u,queueState:p}=Be();Xe({source:"git-page"});const[m,f]=on(),[y,g]=P(null),[x,v]=P("desc"),[b,C]=P("branch"),N=m.get("expanded")==="true",k=()=>{v(de=>de==="desc"?"asc":"desc")},w=Ae(),A=w.data;ee(()=>{a&&c&&a!==c&&w.state==="idle"&&!A&&w.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(a)}`)},[a,c,w,A]);const M=re(()=>{const de=ni(r,t);return Array.from(de.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[r,t]),I=re(()=>{const de=bg(d,t,A);return Array.from(de.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[d,t,A]),D=re(()=>vg(r,t),[r,t]),L=re(()=>b==="uncommitted"?M:I,[b,M,I]),_=re(()=>L.map(([de])=>de),[L]),{expandedUncommitted:S,setExpandedUncommitted:T,toggleFile:F,expandAllUncommitted:q,collapseAllUncommitted:J}=o0(N,_,[]),{diffView:U,diffContent:Y,isLoading:z,handleShowFileDiff:$,handleCloseDiff:E}=i0(c,a),W=(ye=h==null?void 0:h.metadata)==null?void 0:ye.currentRun,H=new Set((W==null?void 0:W.currentEntityShas)||[]),V=new Set(p.jobs.flatMap(de=>de.entityShas||[])),ae=new Set(((bt=p.currentlyExecuting)==null?void 0:bt.entityShas)||[]),{isAnalyzing:O,handleGenerateSimulation:j,handleGenerateAllSimulations:R,isEntityBeingAnalyzed:G,isEntityPending:te}=ii(W==null?void 0:W.currentEntityShas,p),ce=de=>te(de)||V.has(de.sha)||ae.has(de.sha),pe=de=>{de===(s||a)?m.delete("viewBranch"):m.set("viewBranch",de),f(m)},me=de=>{de===o?m.delete("compare"):m.set("compare",de),f(m)},be=()=>{const Fe=L.flatMap(([Oe,Bt])=>Bt.editedEntities||Bt.entities||[]).filter(Oe=>!H.has(Oe.sha)&&!V.has(Oe.sha)&&!ae.has(Oe.sha)&&!te(Oe));R(Fe)},Ce=M.length,Ee=I.length,Se=L.flatMap(([de,Fe])=>Fe.editedEntities||Fe.entities||[]),Pe=Se.filter(de=>de.entityType==="visual"||de.entityType==="library"),Te=Pe.length>0&&Pe.every(de=>H.has(de.sha)),ve=Pe.length>0&&!Te&&Pe.every(de=>V.has(de.sha)||ae.has(de.sha)),Q=O||Te||ve,ue=Te?"Analyzing...":ve?"Queued...":O?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("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. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(u0,{activeTab:b,onTabChange:C,uncommittedCount:Ce,branchCount:Ee})}),a&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:a,onChange:de=>pe(de.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(de=>n("option",{value:de,children:de},de))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:de=>me(de.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(de=>de!==a).map(de=>n("option",{value:de,children:de},de))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children: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:[n("span",{style:{color:"#000000"},children:L.length})," ","modified ",L.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Se.length})," ",Se.length===1?"entity":"entities"]})]}),L.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Us,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:J,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ws,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&a&&n(c0,{files:I,currentBranch:a,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:S,isEntityBeingAnalyzed:G,isEntityQueued:ce,sortOrder:x,onToggleFile:de=>F(de,S,T),onBranchChange:me,onGenerateSimulation:j,onSortChange:k,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:ue}),b==="uncommitted"&&n(d0,{files:M,entityImpactMap:D,expandedFiles:S,isEntityBeingAnalyzed:G,isEntityQueued:ce,projectSlug:u,baseBranch:c,currentBranch:a,sortOrder:x,onToggleFile:de=>F(de,S,T),onShowFileDiff:$,onGenerateSimulation:j,onSortChange:k,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:ue})]}),U&&n(l0,{diffView:U,diffContent:Y,isLoading:z,entities:t,onClose:E}),y&&u&&n(pt,{projectSlug:u,onClose:()=>g(null)})]})})}),g0=Object.freeze(Object.defineProperty({__proto__:null,action:m0,default:f0,loader:p0,meta:h0},Symbol.toStringTag,{value:"Module"})),dy={entry:{module:"/assets/entry.client-I-Wo99C_.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/index-CUM5iXwc.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-DnbDhvTU.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/index-CUM5iXwc.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-BzPgx-xO.js","/assets/useReportContext-DZlYx2c4.js","/assets/loader-circle-TzRHMVog.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/book-open-D4IPYH_y.js","/assets/useToast-ihdMtlf6.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/LogViewer-kgBTLoJD.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/TruncatedFilePath-CDpEprKa.js","/assets/chevron-down-CG65viiV.js","/assets/circle-check-igfMr5DY.js","/assets/triangle-alert-CAD5b1o_.js","/assets/copy-Coc4o_8c.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-DjLxr2JB.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/InlineSpinner-EhOseatT.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/useCustomSizes-BqgrAzs3.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-PePWg17F.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/InteractivePreview-yjIHlOGa.js","/assets/InlineSpinner-EhOseatT.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-DAFqfEDH.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-CtYowLOt.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/InteractivePreview-yjIHlOGa.js","/assets/InlineSpinner-EhOseatT.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-DAFqfEDH.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.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-DHKuQSmR.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/terminal-DbEAHMbA.js","/assets/search-DcAwD_Ln.js","/assets/chevron-down-CG65viiV.js","/assets/book-open-D4IPYH_y.js","/assets/triangle-alert-CAD5b1o_.js"],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.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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)-4S4yPfFw.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/LogViewer-kgBTLoJD.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/useReportContext-DZlYx2c4.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/EntityTypeBadge-CvzqMxcu.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/LoadingDots-BvMu2i-g.js","/assets/loader-circle-TzRHMVog.js","/assets/pause-hjzB7t2z.js","/assets/createLucideIcon-D1zB-pYc.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.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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._-B0h9AqE6.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/InlineSpinner-EhOseatT.js","/assets/InteractivePreview-yjIHlOGa.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/LibraryFunctionPreview-Cq5o8jL4.js","/assets/LoadingDots-BvMu2i-g.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-BX2Ny2Qj.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/CopyButton-jNYXRRNI.js","/assets/LogViewer-kgBTLoJD.js","/assets/useReportContext-DZlYx2c4.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-BqgrAzs3.js","/assets/ReportIssueModal-BzPgx-xO.js","/assets/circle-check-igfMr5DY.js","/assets/triangle-alert-CAD5b1o_.js","/assets/copy-Coc4o_8c.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-DVNJVQgD.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/LoadingDots-BvMu2i-g.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/fileTableUtils-9sMMAiWJ.js","/assets/chevron-down-CG65viiV.js","/assets/search-DcAwD_Ln.js","/assets/loader-circle-TzRHMVog.js","/assets/createLucideIcon-D1zB-pYc.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-JTAjQ54M.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/ScenarioViewer-BX2Ny2Qj.js","/assets/InteractivePreview-yjIHlOGa.js","/assets/useCustomSizes-BqgrAzs3.js","/assets/LogViewer-kgBTLoJD.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/InlineSpinner-EhOseatT.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-BzPgx-xO.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/circle-check-igfMr5DY.js","/assets/triangle-alert-CAD5b1o_.js","/assets/copy-Coc4o_8c.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-CclxrcPK.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.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-BRx8ZGZo.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useLastLogLine-DAFqfEDH.js","/assets/useToast-ihdMtlf6.js","/assets/useReportContext-DZlYx2c4.js","/assets/LogViewer-kgBTLoJD.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/circle-check-igfMr5DY.js","/assets/loader-circle-TzRHMVog.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-CzZySbBE.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/terminal-DbEAHMbA.js","/assets/copy-Coc4o_8c.js","/assets/CopyButton-jNYXRRNI.js","/assets/search-DcAwD_Ln.js","/assets/pause-hjzB7t2z.js","/assets/chevron-down-CG65viiV.js","/assets/book-open-D4IPYH_y.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-Co65J0s3.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.js","/assets/EntityItem-bwuHPyTa.js","/assets/fileTableUtils-9sMMAiWJ.js","/assets/chevron-down-CG65viiV.js","/assets/search-DcAwD_Ln.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/useToast-ihdMtlf6.js","/assets/TruncatedFilePath-CDpEprKa.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/LibraryFunctionPreview-Cq5o8jL4.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-CAD5b1o_.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/EntityTypeBadge-CvzqMxcu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-BK0C1H1T.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.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-BdHOxVfg.js",imports:["/assets/chunk-JZWAC4HX-DB3aFuEO.js","/assets/useReportContext-DZlYx2c4.js","/assets/EntityItem-bwuHPyTa.js","/assets/LogViewer-kgBTLoJD.js","/assets/fileTableUtils-9sMMAiWJ.js","/assets/createLucideIcon-D1zB-pYc.js","/assets/useToast-ihdMtlf6.js","/assets/TruncatedFilePath-CDpEprKa.js","/assets/SafeScreenshot-CwZrv-Ok.js","/assets/LibraryFunctionPreview-Cq5o8jL4.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-CAD5b1o_.js","/assets/EntityTypeIcon-BH0XDim7.js","/assets/EntityTypeBadge-CvzqMxcu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-390cb8fa.js",version:"390cb8fa",sri:void 0},uy="build/client",hy="/",my={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},py=!0,fy=!1,gy=[],yy={mode:"lazy",manifestPath:"/__manifest"},xy="/",by={module:Ol},vy={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:mu},"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:xu},"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:zu},"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:Ju},"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:qh},"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:Zh},"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:ym},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:bm},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Nm},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:Rm},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Fm},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Ym},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Wm},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Vm},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:rp},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:lp},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:hp},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:gp},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:xp},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:jp},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:$p},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:zp},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Bp},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:Zp},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:tf},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:sf},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:lf},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Tf},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:$f},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Yf},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Uf},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:Hf},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:ng},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:sg},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:lg},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:fg},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:yg},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Ag},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:Wg},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Kg},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:s0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:g0}},wy=!1;export{Jc as A,Wc as B,ke as C,gc as D,yc as E,It as F,sc as G,eo as H,to as I,no as J,dc as K,hc as L,uy as M,hy as N,my as O,rc as P,py as Q,fy as R,Rn as S,gy as T,yy as U,xy as V,by as W,vy as X,wy as Y,dy as Z,Zl as a,Dt as b,_t as c,it as d,cn as e,na as f,ra as g,Xs as h,Kl as i,kc as j,Pc as k,ft as l,lt as m,so as n,Dc as o,Ln as p,at as q,oo as r,io as s,Yc as t,mt as u,lo as v,Ft as w,On as x,as as y,Kc as z};