@codeyam/codeyam-cli 0.1.0-staging.1 → 0.1.0-staging.da5baf5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/analyzer-template/.build-info.json +7 -7
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +5 -5
- package/analyzer-template/packages/ai/index.ts +2 -1
- package/analyzer-template/packages/ai/package.json +2 -2
- package/analyzer-template/packages/ai/scripts/ai-test-matrix.mjs +424 -0
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +24 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +6 -16
- package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +197 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +28 -2
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +127 -4
- package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +1 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1821 -542
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.ts +138 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +139 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/DebugTracer.ts +224 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/PathManager.ts +203 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/README.md +294 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +161 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.ts +235 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +14 -6
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/selectBestValue.ts +70 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.ts +113 -0
- package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +36 -0
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityDocumentation.ts +20 -2
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +51 -107
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +56 -160
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +79 -265
- package/analyzer-template/packages/ai/src/lib/generateEntityDocumentation.ts +16 -2
- package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +53 -176
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +53 -154
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +84 -254
- package/analyzer-template/packages/ai/src/lib/generateStatementAnalysis.ts +48 -71
- package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +27 -6
- package/analyzer-template/packages/ai/src/lib/getLLMCallStats.ts +0 -14
- package/analyzer-template/packages/ai/src/lib/modelInfo.ts +15 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +42 -4
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.ts +8 -33
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +54 -62
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +93 -109
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.ts +8 -27
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +33 -38
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +30 -30
- package/analyzer-template/packages/ai/src/lib/types/index.ts +2 -0
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +39 -0
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +52 -6
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +238 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.ts +25 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/index.ts +2 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +8 -10
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +34 -15
- package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +17 -3
- package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +35 -16
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +7 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +9 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +6 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +9 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +15 -7
- package/analyzer-template/packages/aws/package.json +2 -2
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +28 -21
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.ts +18 -11
- package/analyzer-template/packages/generate/src/lib/scenarioComponent.ts +6 -3
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js +5 -3
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/index.d.ts +2 -0
- package/analyzer-template/packages/github/dist/utils/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/index.js +2 -0
- package/analyzer-template/packages/github/dist/utils/index.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts +25 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js +40 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- package/analyzer-template/packages/ui-components/src/scenario-editor/components/DataItemEditor.tsx +1 -1
- package/analyzer-template/packages/utils/dist/utils/index.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/utils/index.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/index.js +2 -0
- package/analyzer-template/packages/utils/dist/utils/index.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts +25 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js +40 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- package/analyzer-template/packages/utils/index.ts +2 -0
- package/analyzer-template/packages/utils/src/lib/Semaphore.ts +42 -0
- package/analyzer-template/packages/utils/src/lib/frameworks/getNextRoutePath.ts +8 -3
- package/analyzer-template/packages/utils/src/lib/frameworks/getRemixRoutePath.ts +2 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.ts +2 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.ts +1 -0
- package/analyzer-template/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.ts +33 -0
- package/analyzer-template/project/constructMockCode.ts +170 -6
- package/analyzer-template/project/reconcileMockDataKeys.ts +13 -0
- package/analyzer-template/project/startScenarioCapture.ts +24 -0
- package/analyzer-template/project/trackGeneratedFiles.ts +41 -0
- package/analyzer-template/project/writeMockDataTsx.ts +125 -4
- package/analyzer-template/project/writeScenarioComponents.ts +175 -45
- package/analyzer-template/project/writeUniversalMocks.ts +72 -10
- package/background/src/lib/virtualized/project/constructMockCode.js +158 -7
- package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +12 -0
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
- package/background/src/lib/virtualized/project/startScenarioCapture.js +18 -0
- package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/trackGeneratedFiles.js +30 -0
- package/background/src/lib/virtualized/project/trackGeneratedFiles.js.map +1 -0
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +95 -3
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenarioComponents.js +130 -28
- package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
- package/background/src/lib/virtualized/project/writeUniversalMocks.js +59 -9
- package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +288 -0
- package/codeyam-cli/scripts/apply-setup.js.map +1 -0
- package/codeyam-cli/scripts/extract-setup.js +130 -0
- package/codeyam-cli/scripts/extract-setup.js.map +1 -0
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +238 -0
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +1 -0
- package/codeyam-cli/src/cli.js +4 -0
- package/codeyam-cli/src/cli.js.map +1 -1
- package/codeyam-cli/src/codeyam-cli.js +0 -0
- package/codeyam-cli/src/commands/debug.js +190 -0
- package/codeyam-cli/src/commands/debug.js.map +1 -0
- package/codeyam-cli/src/commands/init.js +4 -23
- package/codeyam-cli/src/commands/init.js.map +1 -1
- package/codeyam-cli/src/commands/setup-sandbox.js +164 -0
- package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js +6 -6
- package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +8 -0
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- package/codeyam-cli/src/utils/analysisRunner.js +4 -3
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/backgroundServer.js +25 -5
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/cleanupAnalysisFiles.js +2 -2
- package/codeyam-cli/src/utils/cleanupAnalysisFiles.js.map +1 -1
- package/codeyam-cli/src/utils/fileWatcher.js +75 -5
- package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
- package/codeyam-cli/src/utils/queue/job.js +3 -2
- package/codeyam-cli/src/utils/queue/job.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +4 -0
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/webappDetection.js +2 -1
- package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/database.js +63 -2
- package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
- package/codeyam-cli/src/webserver/backgroundServer.js +15 -35
- package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BFRmw1TF.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-Dh-FldQK.js → InteractivePreview-CRfBaL5B.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-BYVx9KFp.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-Dp6DC845.js → LogViewer-CRcT5fOZ.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Bual6h18.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Dj4Mm0AR.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-wtCIkGzq.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/_index-Cjdlwanz.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-Dv3k2aEm.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/chart-column-DOftqM9U.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-De6i8FUT.js +26 -0
- package/codeyam-cli/src/webserver/build/client/assets/circle-alert-0WShkwuc.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/clock-DXui5oLF.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DPFKgE96.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-1Z6D0fLM.js → entity._sha._-BxaXKsIx.js} +10 -10
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BRD2FrH5.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-69R47Ffu.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entityVersioning-DO2gCvXv.js → entityVersioning-Bk_YB1jM.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-B5l8I1m3.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/file-text-fb2mx25c.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-l_Eh9jQG.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-BCnOUEl9.js +12 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-BxkM6Up7.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-BgDzgbQW.js +8 -0
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-DE3HAwpF.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-5579bc45.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/root-o8NMI2bW.js +16 -0
- package/codeyam-cli/src/webserver/build/client/assets/search-BymWwY_X.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-C7G4GDvW.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-Dc4MlMpK.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-Duh3oShE.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BBlyqxij.js → useLastLogLine-AlhS7g5F.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/useToast-XY00p4rI.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/zap-Dra7vum1.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/index-Dpr7o3dP.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BM5nyvlV.js +166 -0
- package/codeyam-cli/src/webserver/build/server/index.js +1 -1
- package/codeyam-cli/src/webserver/build-info.json +5 -5
- package/codeyam-cli/src/webserver/server.js +1 -1
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/templates/codeyam-setup-skill.md +85 -94
- package/package.json +7 -10
- package/packages/ai/index.js +1 -2
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +13 -0
- package/packages/ai/src/lib/analyzeScope.js.map +1 -1
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +6 -15
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
- package/packages/ai/src/lib/astScopes/methodSemantics.js +134 -0
- package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
- package/packages/ai/src/lib/astScopes/paths.js +28 -3
- package/packages/ai/src/lib/astScopes/paths.js.map +1 -1
- package/packages/ai/src/lib/astScopes/processExpression.js +111 -3
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/checkAllAttributes.js +1 -3
- package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1320 -396
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js +137 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +112 -0
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js +176 -0
- package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/PathManager.js +178 -0
- package/packages/ai/src/lib/dataStructure/helpers/PathManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +138 -0
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js +199 -0
- package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +14 -6
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js +62 -0
- package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js +90 -0
- package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js.map +1 -0
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +22 -0
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityDocumentation.js +19 -1
- package/packages/ai/src/lib/generateChangesEntityDocumentation.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +51 -107
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js +55 -156
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarios.js +79 -262
- package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateEntityDocumentation.js +15 -1
- package/packages/ai/src/lib/generateEntityDocumentation.js.map +1 -1
- package/packages/ai/src/lib/generateEntityKeyAttributes.js +53 -176
- package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +52 -152
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +88 -258
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateStatementAnalysis.js +46 -71
- package/packages/ai/src/lib/generateStatementAnalysis.js.map +1 -1
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js +13 -8
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
- package/packages/ai/src/lib/getLLMCallStats.js +0 -14
- package/packages/ai/src/lib/getLLMCallStats.js.map +1 -1
- package/packages/ai/src/lib/modelInfo.js +15 -0
- package/packages/ai/src/lib/modelInfo.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +36 -3
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js +8 -33
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +35 -41
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +59 -72
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js +8 -27
- package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +24 -27
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +21 -22
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/types/index.js +2 -0
- package/packages/ai/src/lib/types/index.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
- package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +45 -5
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +191 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js +16 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js.map +1 -0
- package/packages/analyze/src/lib/asts/sourceFiles/index.js +2 -0
- package/packages/analyze/src/lib/asts/sourceFiles/index.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +6 -8
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +5 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeChange.js +21 -9
- package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeEntity.js +10 -4
- package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeInitial.js +21 -9
- package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +6 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +9 -1
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +5 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +9 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +16 -7
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
- package/packages/generate/src/lib/scenarioComponent.js +5 -3
- package/packages/generate/src/lib/scenarioComponent.js.map +1 -1
- package/packages/utils/index.js +2 -0
- package/packages/utils/index.js.map +1 -1
- package/packages/utils/src/lib/Semaphore.js +40 -0
- package/packages/utils/src/lib/Semaphore.js.map +1 -0
- package/packages/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
- package/packages/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/packages/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/packages/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
- package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
- package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- package/analyzer-template/packages/ai/src/lib/generateEntityDataMap.ts +0 -375
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-GqWwt5wG.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-p0fuyqGQ.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-xwuhwsZH.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bl2IRh55.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-M2QuSHKC.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/_index-CAVtep9Q.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLmzsLsT.js +0 -10
- package/codeyam-cli/src/webserver/build/client/assets/chart-column-B2I7jQx2.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/circle-alert-GwwOAbhw.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/components-CAx5ONX_.js +0 -40
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgyOwWip.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DGy3zrli.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-ChAdTrrU.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-D9L7267w.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-C6FRgjPr.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/files-C3-cQjgv.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-Dp4EB9nv.js +0 -12
- package/codeyam-cli/src/webserver/build/client/assets/globals-Da3jt49-.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-DN7Vr40D.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-172a4629.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/root-COyVTsPq.js +0 -16
- package/codeyam-cli/src/webserver/build/client/assets/search-CvyP_1Lo.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/settings-Hbf8b7J_.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/settings-MZc4XdmE.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/simulations-BMBi0VzO.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useToast-C_VxoXTh.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/zap-B4gsLUZQ.js +0 -1
- package/codeyam-cli/src/webserver/build/client/cy-logo-cli.svg +0 -13
- package/codeyam-cli/src/webserver/build/server/assets/index-eAULANMV.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-lutv16q5.js +0 -161
- package/codeyam-cli/src/webserver/public/cy-logo-cli.svg +0 -13
- package/packages/ai/src/lib/generateEntityDataMap.js +0 -335
- package/packages/ai/src/lib/generateEntityDataMap.js.map +0 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js +0 -17
- package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js.map +0 -1
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import{jsx as n,jsxs as c,Fragment as re}from"react/jsx-runtime";import{PassThrough as fa}from"node:stream";import{createReadableStreamFromReadable as ga}from"@react-router/node";import{ServerRouter as ya,useLocation as br,useNavigate as tt,Link as Z,UNSAFE_withComponentProps as _e,Meta as xa,Links as ba,ScrollRestoration as wa,Scripts as va,useLoaderData as Ie,useRevalidator as nt,Outlet as Ca,data as D,useFetcher as fe,useParams as wr,useSearchParams as bn,useActionData as Na}from"react-router";import{isbot as Sa}from"isbot";import{renderToPipeableStream as Aa}from"react-dom/server";import{useState as k,useEffect as G,useCallback as V,createContext as vr,useContext as Cr,useRef as pe,useMemo as ee}from"react";import{HomeIcon as Ea,GitCommitIcon as qn,File as _a,ActivityIcon as mn,SettingsIcon as Pa,PanelsTopLeftIcon as Ma,ComponentIcon as Ta,CheckCircle2 as $t,Settings as jt,Clock as kt,FileText as $e,CheckCircle as wn,AlertCircle as vn,Pause as Nr,Cog as ka,ListTodo as Ia,BarChart3 as Sr,Code as Wn,Box as Ra,List as $a,Tag as ja,CodeXml as Ar,Loader2 as Be,ChevronDown as hn,Search as Er,X as Da,ChevronLeft as La,ChevronRight as Gn,FolderOpen as Oa,Image as dt,Code2 as Fa,Zap as _r,AlertTriangle as Ya,Plus as za,Circle as Ba}from"lucide-react";import"fetch-retry";import Ua from"better-sqlite3";import{Pool as qa}from"pg";import*as se from"fs";import qe,{existsSync as Wa}from"fs";import*as ae from"path";import le from"path";import{OperationNodeTransformer as Ga,Kysely as Pr,ParseJSONResultsPlugin as Ha,SqliteDialect as Ka,PostgresDialect as Va,sql as Se}from"kysely";import*as Ja from"kysely/helpers/sqlite";import*as Qa from"kysely/helpers/postgres";import he from"typescript";import*as ve from"fs/promises";import ge,{writeFile as Za,readFile as Xa}from"fs/promises";import*as es from"os";import pn from"os";import ts from"prompts";import Dt from"chalk";import Cn,{randomUUID as gt}from"crypto";import{ResizableBox as ns}from"react-resizable";import rs from"openai";import as from"p-queue";import Hn from"p-retry";import{exec as Nn,execSync as Ae,spawn as Sn}from"child_process";import{promisify as An}from"util";import{DynamoDBClient as Wt,PutItemCommand as ss}from"@aws-sdk/client-dynamodb";import{LRUCache as En}from"lru-cache";import"pluralize";import"piscina";import os from"json5";import{marshall as is}from"@aws-sdk/util-dynamodb";import ls from"dotenv";import cs,{EventEmitter as ds}from"events";import{v4 as us}from"uuid";import{fileURLToPath as Mr}from"url";import{Prism as ms}from"react-syntax-highlighter";import{vscDarkPlus as hs}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as ps}from"node:crypto";import fs from"v8";import gs from"react-diff-viewer-continued";const Tr=5e3;function ys(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),m=d&&Sa(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),Tr+1e3);const{pipe:h,abort:p}=Aa(n(ya,{context:a,url:e.url}),{[m](){l=!0;const f=new fa({final(y){clearTimeout(u),u=void 0,y()}}),g=ga(f);r.set("Content-Type","text/html"),h(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const xs=Object.freeze(Object.defineProperty({__proto__:null,default:ys,streamTimeout:Tr},Symbol.toStringTag,{value:"Module"}));function bs({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=k(!1);G(()=>{i(!0)},[]);const l=V(()=>{r?.(e)},[r,e]);return c("button",{className:`
|
|
2
|
+
w-full aspect-square p-3 cursor-pointer focus:outline-none
|
|
3
|
+
flex flex-col items-center justify-center gap-1 text-[#626262]
|
|
4
|
+
hover:bg-[#d8d8d8] text-xs font-ibmPlexSans uppercase
|
|
5
|
+
`,onClick:l,children:[n("div",{className:`${t?"bg-primary-100 text-cygray-10":""} w-10 h-10 rounded-lg flex items-center justify-center`,children:o&&a}),n("span",{className:`${t?"text-primary-100":""} whitespace-nowrap`,children:s})]})}const ws="/assets/cy-logo-cli-C1gnJVOL.svg";function vs(){const e=br(),t=tt(),[r,a]=k(),s={width:"24px",height:"24px",strokeWidth:1.5},o=[{id:"dashboard",icon:n(Ea,{style:s}),link:"/",name:"Dashboard"},{id:"simulations",icon:c("svg",{width:"24",height:"24",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:s,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"},{id:"git",icon:n(qn,{style:s}),link:"/git",name:"Git"},{id:"files",icon:n(_a,{style:s}),link:"/files",name:"Files"},{id:"activity",icon:n(mn,{style:s}),link:"/activity",name:"Activity"},{id:"settings",icon:n(Pa,{style:s}),link:"/settings",name:"Settings"},{id:"commits",icon:n(qn,{style:s}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Ma,{style:s}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Ta,{style:s}),link:"/components",name:"Components",hidden:!0}],i=V(l=>{const d=o.find(m=>m.id===l);d?.link&&t(d.link),a(m=>m===l?void 0:l)},[o,t]);return G(()=>{const l={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[d,m]of Object.entries(l))if(m.some(u=>u==="/"?e.pathname==="/":e.pathname.includes(u))){a(d);return}a(void 0)},[e]),n("div",{id:"sidebar",className:"relative w-full h-screen bg-cygray-30 flex flex-col justify-between py-3",children:c("div",{className:"w-full h-full flex flex-col items-center",children:[n("div",{children:n(Z,{to:"/",className:"flex items-center justify-center h-20",children:n("img",{src:ws,alt:"CodeYam",className:"h-8"})})}),o.filter(l=>!l.hidden).map(l=>n(bs,{id:l.id,selected:l.id===r,onClick:i,icon:l.icon,name:l.name},`sidebar-button-${l.id}`))]})})}const kr=vr(void 0);function Cs({children:e}){const[t,r]=k([]),a=V((o,i="info",l=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,m])},[]),s=V(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(kr.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function _n(){const e=Cr(kr);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Ns({toast:e,onClose:t}){G(()=>{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 c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Ss({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
6
|
+
@keyframes slideIn {
|
|
7
|
+
from {
|
|
8
|
+
transform: translateX(400px);
|
|
9
|
+
opacity: 0;
|
|
10
|
+
}
|
|
11
|
+
to {
|
|
12
|
+
transform: translateX(0);
|
|
13
|
+
opacity: 1;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
`}),e.map(r=>n(Ns,{toast:r,onClose:t},r.id))]})}function Ye(e,t){const[r,a]=k(""),[s,o]=k(!1),[i,l]=k(null),[d,m]=k(!1);G(()=>{t&&(m(!1),o(!1),l(null))},[t]),G(()=>{if(!e||!t){t||a("");return}const h=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
|
|
17
|
+
`).filter(x=>x.length>0);if(y.length<3){o(!1),m(!1),l(null),a("");return}const b=y.filter(x=>x.includes("CodeYam Log Level 1"));if(b.length>0){const x=b[b.length-1];a(x.replace(/.*CodeYam Log Level 1: /,""))}const w=y.find(x=>x.includes("$$INTERACTIVE_SERVER_URL$$:"));if(w){const x=w.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(x),m(!0)}y.some(x=>x.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=V(()=>{a(""),o(!1),l(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function rt({projectSlug:e,onClose:t}){const[r,a]=k("Loading logs..."),[s,o]=k(!0),[i,l]=k(!0),[d,m]=k("all"),u=pe(null);return G(()=>{const h=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
|
|
18
|
+
`).filter(y=>{if(y.length===0)return!1;const b=y.match(/^.*CodeYam Log Level (\d+):/);return!!b&&Number(b[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
19
|
+
`))}i&&u.current&&setTimeout(()=>{u.current?.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),s){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),G(()=>{const h=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:h=>m(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function As({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){const[d,m]=k(!1),[u,h]=k(!1),[p,f]=k(!1),[g,y]=k(null),b=!!i||o.length>0,w=!!i,x=i?.entities||r,C=!!e?.analysisCompletedAt;e?.readyToBeCaptured,e?.capturesCompleted;const v=e?.currentEntityShas&&e.currentEntityShas.length>0,S=b,{lastLine:N,isCompleted:E}=Ye(t,S),A=w||S&&!E&&!b,I=(()=>{if(S)return!1;const O=Date.now()-30*1e3;if(e?.createdAt&&v){const Y=e.analysisCompletedAt||e.createdAt;if(new Date(Y).getTime()>O)return!0}if(l.length>0){const Y=l[0],J=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt;if(J&&new Date(J).getTime()>O)return!0}return!1})(),T=(()=>{const O=Date.now()-1440*60*1e3;if(e?.createdAt&&v){const Y=e.analysisCompletedAt||e.createdAt;if(new Date(Y).getTime()>O)return!0}if(l.length>0){const Y=l[0],J=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt;if(J&&new Date(J).getTime()>O)return!0}return!1})(),M=a||A||s>0||I;G(()=>{const R=i?.id||null;M?R!==g&&(h(!0),f(!1),g!==null&&y(null)):(g!==null&&y(null),!T&&u&&!p&&h(!1))},[M,T,u,p,g,i?.id]);const P=()=>i?`Analyzing${o.length>0?` (+${o.length} queued)`:""}`:o.length>0?`${o.length} job${o.length>1?"s":""} queued`:A?C?"Capture in Progress":"Analysis in Progress":I?"Recently completed":"Idle",L=()=>A?"settings":s>0?"clock":I?"check":"activity";return c(re,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded-lg shadow-lg border-2 transition-all duration-200 border-gray-300 ${u?"min-w-[400px] max-w-[600px]":"w-auto"}`,style:M?{borderColor:"#005C75"}:{},children:[!u&&c("div",{onClick:()=>{h(!0),f(!0),y(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors rounded-lg",title:"Click to expand",children:[n("span",{className:`${A?"animate-spin":""}`,children:L()==="activity"?n(mn,{style:{width:"20px",height:"20px",strokeWidth:1.5}}):L()==="check"?n($t,{size:20,style:{color:"#10B981",strokeWidth:1.5}}):L()==="settings"?n(jt,{size:20,style:{strokeWidth:1.5}}):n(kt,{size:20,style:{strokeWidth:1.5}})}),c("span",{className:"text-sm font-medium text-gray-700",children:["Activity: ",P()]})]}),u&&c("div",{children:[c("div",{className:"flex justify-between items-center p-3 w-full",children:[c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>{h(!1),y(i?.id||null)},className:"p-1.5 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors shadow-sm flex items-center justify-center",title:"Collapse","aria-label":"Collapse notification",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("div",{className:`${A?"animate-spin":""}`,children:A?n(jt,{size:24,style:{strokeWidth:1.5}}):I?n($t,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(mn,{style:{width:"24px",height:"24px",strokeWidth:1.5}})}),n("div",{className:"flex-1 min-w-0",children:n("h3",{className:"text-sm font-bold text-gray-900 mb-1",children:A?C?"Capture in Progress":"Analysis in Progress":I?"Analysis Complete":"Activity"})})]}),n("div",{children:n("button",{onClick:()=>m(!0),className:"px-3 py-1.5 text-white rounded-md text-xs font-semibold transition-colors whitespace-nowrap",style:{backgroundColor:"#005C75"},onMouseEnter:R=>R.currentTarget.style.backgroundColor="#004560",onMouseLeave:R=>R.currentTarget.style.backgroundColor="#005C75",title:"View full analysis logs",children:"View Logs"})})]}),c("div",{className:"px-4 pb-4 border-t border-gray-200 pt-3",children:[!M&&!T&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs text-gray-600 mb-2",children:"No recent analysis activity. Start an analysis to see progress here."}),c("div",{className:"text-xs text-gray-500 space-y-1",children:[n("div",{children:'• Click "Analyze" on any entity in the Git or Files view'}),c("div",{children:["• Or run"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"codeyam analyze"})," ","from the command line"]})]})]}),A&&C&&(e?.readyToBeCaptured??0)>0&&c("div",{className:"mb-3 border rounded-md p-2",style:{backgroundColor:"#E8F4F8",borderColor:"#B3D9E8"},children:[n("p",{className:"text-xs font-semibold mb-1",style:{color:"#003D52"},children:"Capture Progress:"}),c("p",{className:"text-xs",style:{color:"#005C75"},children:[e?.capturesCompleted??0," of"," ",e?.readyToBeCaptured??0," entities captured"]})]}),A&&x.length>0&&c("div",{className:"mb-3",children:[c("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:[i?"Analyzing":C?"Capturing":"Analyzing"," ",x.length===1?"Entity":"Entities",":"]}),n("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:x.map(R=>c(Z,{to:`/entity/${R.sha}`,className:"flex items-center gap-1.5 text-xs font-medium truncate hover:underline",style:{color:"#005C75"},title:`${R.name} - ${R.filePath}`,children:[n($e,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[R.name,c("span",{className:"text-gray-500 ml-1",children:["(",R.filePath,")"]})]})]},R.sha))})]}),A&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs font-semibold text-gray-700 mb-1",children:"Current Step:"}),n("p",{className:"text-xs font-mono text-gray-600 break-words",children:N||"Starting analysis..."})]}),o.length>0&&i&&c("div",{className:"mb-3",children:[c("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:["Queued (",o.length,"):"]}),n("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.map(R=>c("div",{className:"space-y-1",children:[R.entities.length>0?R.entities.slice(0,2).map(O=>c(Z,{to:`/entity/${O.sha}`,className:"flex items-center gap-1.5 text-xs font-medium truncate hover:underline",style:{color:"#005C75"},title:`${O.name} - ${O.filePath}`,children:[n(kt,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[O.name,c("span",{className:"text-gray-500 ml-1",children:["(",O.filePath,")"]})]})]},O.sha)):c("div",{className:"flex items-center gap-1.5 text-xs text-gray-600 truncate",children:[n(kt,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),R.entities.length," ",R.entities.length===1?"entity":"entities"]}),R.entities.length>2&&c("div",{className:"text-xs text-gray-500 italic pl-4",children:["+",R.entities.length-2," more"]})]},R.id))})]}),T&&l.length>0&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:"Recently Completed:"}),n("div",{className:"space-y-2",children:l.slice(0,3).map((R,O)=>{const Y=R.entities||[];Y.length||R.currentEntityShas?.length||R.entityCount;const J=R.analysisCompletedAt||R.archivedAt||R.createdAt||"",F=(()=>{if(!J)return"";const q=Date.now()-new Date(J).getTime(),K=Math.floor(q/6e4),$=Math.floor(q/36e5);return $>0?`${$}h ago`:K>0?`${K}m ago`:"just now"})();return n("div",{className:"text-xs bg-gray-50 rounded-md p-2",children:c("div",{className:"flex justify-between items-start mb-1",children:[n("div",{children:Y.length>0&&c("div",{className:"text-gray-600 text-[10px] space-y-0.5",children:[Y.slice(0,3).map(q=>c("div",{className:"flex items-center gap-1 truncate",children:[c(Z,{to:`/entity/${q.sha}`,className:"flex items-center gap-1 hover:underline truncate",style:{color:"#005C75"},children:[n($e,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),n("span",{className:"truncate",children:q.name})]}),c("span",{className:"text-gray-500 ml-1",children:["(",q.filePath,")"]})]},q.sha)),Y.length>3&&c("div",{className:"text-gray-500",children:["+",Y.length-3," more"]})]})}),n("div",{className:"text-gray-500 text-[10px]",children:F})]})},O)})})]}),n("div",{className:"mt-3 pt-3 border-t border-gray-200",children:n(Z,{to:"/activity",className:"text-xs font-medium hover:underline",style:{color:"#005C75"},children:"View All Activity →"})})]})]})]}),d&&t&&n(rt,{projectSlug:t,onClose:()=>m(!1)})]})}function Ce(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function yt(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:m,updated_at:u,...h}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(je):void 0,g=d?Ge(d):void 0;return Ce({...h,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:m,updatedAt:u})}function Pn(e){return Ce({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 Mn(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:m,...u}=e;return Ce({...u,branches:t?t.map(Xe):void 0,files:r?r.map(Pn):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function Es(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Ce({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:l})}function _s(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:l,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Ce({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:l,user:m})}function Ir(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,m=s?je(s):void 0,u=o?o.map(Es):void 0,h=i?i.map(_s):void 0;return Ce({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:m,userScenarios:u,comments:h})}function Ps(e){return Ce({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?je(e.analysis):void 0,entity:e.entity?yt(e.entity):void 0,branch:e.branch?Xe(e.branch):void 0,createdAt:e.created_at})}function je(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:m,entity:u,commit:h,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:b,branch_commit_sha:w,committed_at:x,completed_at:C,created_at:v,updated_at:S,indirect:N,...E}=e,A=u?yt(u):void 0,I=m?Pn(m):void 0,T=p?Mn(p):void 0,M=h?Ge(h):void 0,P=f?f.map(Ir):void 0,L=g?g.map(Ps):void 0,_=L?L.map(R=>R.branch):void 0;return Ce({...E,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:A,file:I,commit:M,project:T,scenarios:P,analysisBranches:L,branches:_,dependencyAnalyzedTreeSha:y,analyzedTreeSha:b,branchCommitSha:w,committedAt:x,completedAt:C,createdAt:v,updatedAt:S,indirect:!!N})}function Tn(e){return Ce({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Ge(e.commit):void 0,branch:e.branch?Xe(e.branch):void 0})}function Ms(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return Ce({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function Ge(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:m,analyses:u,entities:h,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,b=a?Xe(a):void 0,w=i?Xe(i):void 0,x=s?.length>0?Ms(s[s.length-1]):void 0,C=(u??[]).map(je),v=(h??[]).map(yt),S=p?.length>0?p.map(Tn):void 0;return m&&(m.username=m.preferredUsername??m.username),Ce({...y,projectId:t,branchId:r,branch:b,backgroundJob:x,mergedBranchId:o,mergedBranch:w,aiMessage:l,htmlUrl:d,author:m,analyses:C,entities:v,commitBranches:S,committedAt:f,analyzedAt:g})}function Xe(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:l,primary:d,...m}=e,u=a?a.map(Ge):void 0,h=s?s.flatMap(p=>je(p.analysis)):void 0;return Ce({...m,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}class Ts{#e=new ks;transformQuery(t){return this.#e.transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}class ks extends Ga{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 z=()=>null,Is={analyzed_at:z(),configuration:z(),content_changed_at:z(),created_at:z(),description:z(),github_token:z(),id:z(),metadata:z(),name:z(),path:z(),slug:z(),team_id:z(),updated_at:z()},Rs=Object.keys(Is),$s={active:z(),analysis_id:z(),branch_id:z(),created_at:z(),entity_sha:z(),id:z()},js=Object.keys($s),Ds={active_at:z(),content_changed_at:z(),created_at:z(),id:z(),metadata:z(),name:z(),primary:z(),project_id:z(),ref:z(),sha:z(),updated_at:z()},Rr=Object.keys(Ds),Ls={ai_message:z(),analyzed_at:z(),author_github_username:z(),branch_id:z(),committed_at:z(),created_at:z(),files:z(),html_url:z(),id:z(),merged_branch_id:z(),message:z(),metadata:z(),project_id:z(),sha:z(),title:z(),url:z()},Os=Object.keys(Ls),Fs={commit_id:z(),created_at:z(),description:z(),documentation:z(),entity_type:z(),file_id:z(),file_path:z(),metadata:z(),name:z(),project_id:z(),quality:z(),sha:z(),updated_at:z()},$r=Object.keys(Fs),Ys={active:z(),branch_id:z(),entity_sha:z()},zs=Object.keys(Ys),Bs={created_at:z(),deleted:z(),id:z(),metadata:z(),name:z(),path:z(),project_id:z(),updated_at:z()},Us=Object.keys(Bs),qs={analysis_id:z(),approved:z(),created_at:z(),description:z(),id:z(),metadata:z(),name:z(),previous_version_id:z(),project_id:z()},kn=Object.keys(qs),Ws=!!We("ENABLE_QUERY_LOGGING"),Gs=!!We("ENABLE_QUERY_ERROR_LOGGING");We("USE_LOCAL_POSTGRESQL_FOR_TESTING");let St;function ce(){if(!St){const e=Dr();if(e==="sqlite")St=Hs();else if(e==="postgresql")St=Ks();else throw new Error(`Unknown database type: ${e}`)}return St}function Hs(e){if(e||(e=We("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=se.existsSync(e),r=ae.dirname(e);if(!se.existsSync(r))se.mkdirSync(r,{recursive:!0,mode:493});else try{se.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new Ua(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 Pr({dialect:new Ka({database:a}),plugins:[new Ha,new Ts],log:jr})}function Ks(){const e=Js();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new qa({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Pr({dialect:new Va({pool:t}),log:jr})}let rn=null;function He(){return rn||(rn=Vs(Dr())),rn}function jr(e){e.level==="error"?Gs&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Ws&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Vs(e){if(e==="sqlite")return Ja;if(e==="postgresql")return Qa;throw new Error(`Unknown database type: ${e}`)}function Dr(){if(We("SQLITE_PATH"))return"sqlite";if(We("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Js(){const e=We("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function We(e){return typeof window<"u"?window.env?.[e]:process.env[e]}var xt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(xt||{});const Gt="Default Scenario";let Qs="<main>";function Zs(){return Qs}function oe(...e){const t=Zs(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
|
|
20
|
+
${s.stack}`:typeof s=="object"?Xs(s):String(s)}).filter(Boolean).join(`
|
|
21
|
+
`),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
22
|
+
`);return}console.log(a.replace(/\n/g,"\r"))}function Xs(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(l=>{const d=r(l,s);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,s):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(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 Lt(e,t){try{let r=function(o){if(he.isFunctionDeclaration(o)&&ut(o)){const i=o.name?.text||"default",l=o.getText(a),d=an(o);s.push({name:i,code:l,sha:Je(t,i,l),entityType:"function",isDefault:d})}else if(he.isClassDeclaration(o)&&ut(o)){const i=o.name?.text||"default",l=o.getText(a),d=an(o),m=l.includes("React.")||l.includes("jsx")||l.includes("tsx");s.push({name:i,code:l,sha:Je(t,i,l),entityType:m?"component":"class",isDefault:d})}else if(he.isInterfaceDeclaration(o)&&ut(o)){const i=o.name.text,l=o.getText(a);s.push({name:i,code:l,sha:Je(t,i,l),entityType:"interface",isDefault:!1})}else if(he.isTypeAliasDeclaration(o)&&ut(o)){const i=o.name.text,l=o.getText(a);s.push({name:i,code:l,sha:Je(t,i,l),entityType:"type",isDefault:!1})}else if(he.isVariableStatement(o)&&ut(o)){const i=an(o);o.declarationList.declarations.forEach(l=>{if(he.isIdentifier(l.name)){const d=l.name.text,m=o.getText(a),u=l.initializer?.getText(a)||"",h=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&u.includes("=>")&&(u.includes("<")||u.includes("React."));s.push({name:d,code:m,sha:Je(t,d,m),entityType:h?"component":"variable",isDefault:i})}})}else if(he.isExportAssignment(o)){const i=o.getText(a);s.push({name:"default",code:i,sha:Je(t,"default",i),entityType:"unknown",isDefault:!0})}he.forEachChild(o,r)};const a=he.createSourceFile(t,e,he.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function ut(e){if(!he.canHaveModifiers(e))return!1;const t=he.getModifiers(e);return t?t.some(r=>r.kind===he.SyntaxKind.ExportKeyword):!1}function an(e){if(!he.canHaveModifiers(e))return!1;const t=he.getModifiers(e);return t?t.some(r=>r.kind===he.SyntaxKind.DefaultKeyword):!1}function Je(e,t,r){const a=Cn.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function Ht(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}function eo(e){const{jsonObjectFrom:t}=He();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 to({ids:e,analysisId:t}){const r=ce();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 oe("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 oe("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function no(...e){try{const t=Cn.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 Kn(e,t){return t.map(r=>ro(e,r))}function ro(e,t){return Se` ${Se.ref(e)}.${Se.ref(t)}`.as(t)}function ao(e,t,r){return t.map(a=>so(e,a,r))}function so(e,t,r){return Se` ${Se.ref(e)}.${Se.ref(t)}`.as(`_cy_${r}:${t}`)}function oo(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const io=50;function lo(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 Vn({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:l}){const d=ce(),{jsonObjectFrom:m,jsonArrayFrom:u}=He();let h=d.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(o){if(o.length===0)return null;h=h.where("commit_id","in",o)}return a&&(h=h.where("entity_name","=",a)),s&&(h=h.where("entity_sha","in",s)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),d.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[m(p.selectFrom("entities").select(Kn("entities",$r)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),u(p.selectFrom("scenarios").select(Kn("scenarios",kn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),u(p.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function pt(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:m}])=>m?.length>0);let l=[];if(i){const[d,{arr:m,key:u}]=i,h=lo(m,io),p=[];for(let f=0;f<h.length;f++){const g=h[f],b=await Vn({...e,[u]:g}).execute();b&&p.push(...b)}l=p}else{const m=await Vn(e).execute();if(!m||m.length===0)return oe("CodeYam: No analyses found",null,e),null;l=m}return l.length===0?null:l.map(je)}catch(o){return oe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function co(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=He();let s=e.selectFrom("analysis_branches").select(js).select(o=>a(o.selectFrom("branches").select(Rr).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function ze({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}){const f=ce();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):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:y,jsonArrayFrom:b}=He();g=g.select(x=>{const C=[];return C.push(y(x.selectFrom("entities").select($r).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&C.push(y(x.selectFrom("files").select(Us).whereRef("files.id","=","analyses.file_id")).as("file")),m&&C.push(y(x.selectFrom("projects").select(Rs).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&C.push(b(x.selectFrom("scenarios").select(kn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&C.push(co(x,v=>v.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&C.push(y(x.selectFrom("commits").select(Os).select(v=>eo(v).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const w=await g.executeTakeFirst();return w?je(w):(oe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null)}catch(g){return oe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null}}async function Lr({projectId:e,ids:t,names:r,includeInactive:a}){const s=ce();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(Xe)}catch(o){return oe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function uo({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ce();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,m=>m.select(ao("branches",Rr,"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 l=await i.execute();return!l||l.length===0?null:l.map(m=>oo(m,"branch")).map(Tn)}catch(i){return oe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function mo(e){if(e.length===0)return new Map;const t=ce();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 oe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function ho(e){if(e.length===0)return new Map;const t=ce(),{jsonObjectFrom:r,jsonArrayFrom:a}=He();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(kn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(s){return oe("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function po(e){if(e.length===0)return new Map;const t=ce();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 oe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Ot({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10}){if(!e&&!r)throw new Error("Must provide projectId or ids");const i=ce(),{jsonObjectFrom:l}=He();try{let d=i.selectFrom("commits").selectAll("commits").select(y=>[l(y.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",y.ref("commits.author_github_username"))).as("author")]);if(e&&(d=d.where("project_id","=",e)),r){if(r.length===0)return[];d=d.where("id","in",r)}if(a){if(a.length===0)return[];d=d.where("sha","in",a)}if(s&&s.length>0){const y=Se.join(s.map(b=>Se`${b}`),Se`, `);d=d.where(Se`
|
|
23
|
+
EXISTS (
|
|
24
|
+
SELECT 1
|
|
25
|
+
FROM json_each(${Se.ref("commits.files")}) AS f
|
|
26
|
+
WHERE json_extract(f.value, '$.fileName') IN (${y})
|
|
27
|
+
)
|
|
28
|
+
`)}t&&(d=d.where("branch_id","=",t));const m=await d.orderBy("committed_at","desc").limit(o).execute();if(!m||m.length===0)return[];const u=m.map(y=>y.id),[h,p,f]=await Promise.all([mo(u),ho(u),po(u)]);return m.map(y=>{const b=y.branch_id?h.get(y.branch_id):void 0,w=y.merged_branch_id?h.get(y.merged_branch_id):void 0,x=p.get(y.id)||[],C=f.get(y.id)||[];return{...y,branch:b,mergedBranch:w,analyses:x,entities:C}}).map(Ge)}catch(d){return oe("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function et({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const l=[];for(let d=0;d<o.length;d+=50){const m=o.slice(d,d+50),u=await et({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:m});u&&l.push(...u)}return l}const i=ce();try{const d=await i.selectFrom("entities").selectAll("entities").$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!s,m=>m.where("entities.name","in",s)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!d||d.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):d.map(yt)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function fo(e,t){const{jsonArrayFrom:r}=He();let a=e.selectFrom("entity_branches").select(zs);return t&&(a=t(a)),r(a)}async function Or({projectId:e,sha:t}){const r=ce();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>fo(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?yt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&oe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return oe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const sn=1e3;async function Fr({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const m=t.slice(d,d+50),u=await Fr({projectId:e,filePaths:m,fileIds:r,fileNames:a});u&&l.push(...u)}return l}const s=ce(),o=[];let i=0;try{for(;;){let l=s.selectFrom("files").selectAll().where("project_id","=",e).limit(sn).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(a){if(a.length===0)return[];l=l.where("name","in",a)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<sn))break;i+=sn}return o?.map(Pn)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function go({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ce().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=Mn(l);return a&&(d.files=await Fr({projectId:d.id})),r&&(d.branches=await Lr({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Ft(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]=Ft(o,s):s!==void 0&&(r[a]=s)}return r}async function Qe({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ce().transaction().execute(async i=>{const l=await i.selectFrom("commits").selectAll().$if(!!e,u=>u.where("id","=",e)).$if(!!t,u=>u.where("sha","=",t)).executeTakeFirst();if(!l)return oe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)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:",d.currentRun?.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=Ft(r??{},{currentRun:a});else if(!r&&!o)return d;const m=r?Ft(d,r):d;if(s&&m.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",m.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${m.currentRun.analyzerPid}, capture=${m.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${m.currentRun.analysesCompleted}, captures=${m.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${m.historicalRuns?.length||0}`);const u={...m.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(u,null,2)),m.historicalRuns=[...m.historicalRuns||[],u],console.log(`[updateCommitMetadata] Historical runs after archiving: ${m.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(m.historicalRuns.map(h=>({entityShas:h.currentEntityShas,archivedAt:h.archivedAt,completed:{analyses:h.analysesCompleted,captures:h.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(m,Ge(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",l.id).returningAll().executeTakeFirst()?m:(oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(u){return oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,u),d}})}catch(i){return oe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function Yr(e,t,r="analysis"){try{return await ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return oe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=je(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(oe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return oe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function bt(e,t,r="capture"){try{return await ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return oe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=je(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(oe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return oe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function yo({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ce().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 oe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const l=r?Ft(i,r):i;a&&await a(l,Mn(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return oe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}function xo(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,...l}=e;return delete l.userScenarios,delete l.comments,"created_at"in l&&delete l.created_at,{...l,id:t??gt(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function bo(e){if(e.length===0)return[];const t=ce(),r=e.map(xo);try{return(await t.insertInto("scenarios").values(r).onConflict(Ht(r[0],"id",["created_at"])).returningAll().execute()).map(Ir)}catch(a){return oe("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function wo(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??gt(),commit_id:r,branch_id:a}}async function Jn(e){if(e.length===0)return[];const t=ce(),r=e.map(wo);try{return(await t.insertInto("commit_branches").values(r).onConflict(Ht(r[0],"id",["created_at"])).returningAll().execute()).map(Tn)}catch(a){return oe("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function vo(e,t){const r=ce(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(Ht(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return oe("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}function Co(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:m,author:u,metadata:h,files:p,...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??gt(),project_id:a??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u?.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:m}}async function No({projectId:e,commits:t}){const r=ce();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d?.username&&d?.avatarUrl&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await vo(i,a[i]);const s=t.map(i=>Co(i,e));return(await r.insertInto("commits").values(s).onConflict(Ht(s[0],"id",["created_at"])).returningAll().execute()).map(Ge)}catch(a){return oe("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const Yt=ae.join(es.homedir(),".codeyam","secrets.json"),zt=ae.join(process.cwd(),".codeyam","secrets.json");async function at(){let e={};try{if(se.existsSync(zt)){const o=await ve.readFile(zt,"utf8");e=JSON.parse(o)}}catch{console.warn(Dt.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(se.existsSync(Yt)){const o=await ve.readFile(Yt,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(Dt.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 So(e,t=!0){const r=t?Yt:zt,a=ae.dirname(r);await ve.mkdir(a,{recursive:!0}),await ve.writeFile(r,JSON.stringify(e,null,2)),await ve.chmod(r,384)}function Ao(e=!0){return e?Yt:zt}async function Qn(){const e=await at(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Eo(e){console.log(),console.log(Dt.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await ts({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 _o(e=!0){const t=await Qn();if(t.isValid)return t.secrets;const r=await Eo(t.missing),s={...await at(),...r};await So(s,e);const o=Ao(e);return console.log(Dt.green(`✓ Configuration saved to ${o}`)),(await Qn()).secrets}function zr(e=process.cwd()){let t=ae.resolve(e);const r=ae.parse(t).root;for(;t!==r;){const s=ae.join(t,".codeyam","config.json");if(se.existsSync(s))return t;t=ae.dirname(t)}const a=ae.join(r,".codeyam","config.json");return se.existsSync(a)?r:null}let Br=zr();function ie(){return Br}function Po(e){Br=e}function Ur(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const Mo={"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>`};Ur(Mo);const To={"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>`};Ur(To);function fn(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)}const a={...e};for(const s in t)if(t[s]===null)delete a[s];else if(Array.isArray(t[s])){a[s]=[];for(let o=0;o<t[s].length;o++){const i=t[s][o];typeof i=="object"&&i!==null?a[s][o]=fn(a?.[s]?.[o],i,r):a[s][o]=i}}else typeof t[s]=="object"&&t[s]!==null?a[s]=fn(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 ko({projectId:e,commit:t,branch:r}){let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await uo({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=o.sort((d,m)=>(d.branch.metadata?.permanent?.order??999)-(m.branch.metadata?.permanent?.order??999))[0]?.branch,a&&r.metadata?.permanent?.order!==void 0&&(r.metadata?.permanent?.order<=a.metadata?.permanent?.order?a=r:s.active=!1);const l=o.filter(d=>d.active&&d.branch.id!==a.id||!d.active&&d.branch.id===a.id);l.length>0&&await Jn(l.map(d=>({...d,active:d.branchId===a.id})))}o?.find(l=>l.branchId===s.branchId)||await Jn([s])}function st(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=ie();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return le.join(e,".codeyam","db.sqlite3")}async function we(){const e=await _o();process.env.SQLITE_PATH=st(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ee(e){await we();const t=await go({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const a=(await Lr({projectId:t.id,names:["_local"]}))?.[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 Io(e,t,r){await we();const a=no(`${e.slug}-local-${Date.now()}-${Math.random()}`),s={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:r.map(i=>({fileName:i,status:"modified",patch:""})),metadata:{baseline:!1,receivedAt:new Date().toISOString()}},o=await No({projectId:e.id,commits:[s]});if(!o||o.length===0)throw new Error("Failed to create fake commit");return await ko({projectId:e.id,commit:o[0],branch:t}),o[0]}async function wt(){await we();const e=await et({});if(!e||e.length===0)return e;const t=e.filter(l=>!l.metadata?.isSuperseded),r=t.map(l=>l.sha),a=t.map(l=>l.metadata?.previousVersionWithAnalyses).filter(l=>!!l),s=[...new Set([...r,...a])],o=await pt({entityShas:s}),i=new Map;if(o)for(const l of o)i.has(l.entitySha)||i.set(l.entitySha,[]),i.get(l.entitySha).push(l);return t.map(l=>{const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const m=l.metadata?.previousVersionWithAnalyses;if(m){const u=i.get(m)||[];return{...l,analyses:u}}return{...l,analyses:[]}})}async function Kt(e,t){await we();const r=await pt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await Or({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function Re(e){await we();const t=await Pe();if(!t)return null;const{project:r}=await Ee(t);return await Or({projectId:r.id,sha:e})}async function qr(e){await we();const t=[],r=[];if(e.metadata?.importedExports&&e.metadata.importedExports.length>0){const a=e.metadata.importedExports;for(const s of a){if(!s.filePath||!s.name)continue;const o=await et({projectId:e.projectId,filePaths:[s.filePath],names:[s.name]});if(o&&o.length>0){const i=o[0],l=await pt({entityShas:[i.sha],limit:1});let d,m,u;if(l&&l.length>0&&l[0].scenarios){const h=l[0],p=h.scenarios||[],f=p.length,g=p.find(b=>b.metadata?.screenshotPaths?.[0]);g&&(d=g.metadata?.screenshotPaths?.[0],m=g.name),u={status:i.metadata?.previousVersionWithAnalyses||h.entitySha!==i.sha?"out_of_date":"up_to_date",scenarioCount:f,timestamp:h.createdAt?new Date(h.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else u={status:"not_analyzed"};t.push({...i,screenshotPath:d,scenarioName:m,analysisStatus:u})}}}if(e.metadata?.importedBy){const a=[];for(const s in e.metadata.importedBy)for(const o in e.metadata.importedBy[s]){const i=e.metadata.importedBy[s][o];i.shas&&a.push(...i.shas)}if(a.length>0){const s=await et({projectId:e.projectId,shas:a});if(s)for(const o of s){const i=await pt({entityShas:[o.sha],limit:1});let l,d,m;if(i&&i.length>0&&i[0].scenarios){const u=i[0],h=u.scenarios||[],p=h.length,f=h.find(y=>y.metadata?.screenshotPaths?.[0]);f&&(l=f.metadata?.screenshotPaths?.[0],d=f.name),m={status:o.metadata?.previousVersionWithAnalyses||u.entitySha!==o.sha?"out_of_date":"up_to_date",scenarioCount:p,timestamp:u.createdAt?new Date(u.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else m={status:"not_analyzed"};r.push({...o,screenshotPath:l,scenarioName:d,analysisStatus:m})}}}return{importedEntities:t,importingEntities:r}}async function Pe(){try{const e=ie();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await ge.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Ke(){await we();try{const e=await Pe();if(!e)return null;const{project:t,branch:r}=await Ee(e),a=await Ot({projectId:t.id,branchId:r.id,limit:1});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Wr(){try{const e=ie();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await ge.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Gr(e){try{const t=ie();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=le.join(t,e.filePath);return await ge.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Hr(e){if(await we(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await et({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await pt({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,l]of s.entries())l.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,l)=>{const d=i.analyses[0]?.createdAt||i.createdAt||"",m=l.analyses[0]?.createdAt||l.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),o}async function Kr(e){try{const t=ie();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=le.join(t,".codeyam","config.json"),a=await ge.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await ge.writeFile(r,i,"utf8"),s.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await yo({projectSlug:s.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Ro=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:wt,getAnalysesForEntity:Kt,getCurrentCommit:Ke,getEntityBySha:Re,getEntityCodeFromFilesystem:Gr,getEntityHistory:Hr,getProjectConfig:Wr,getProjectSlug:Pe,getRelatedEntities:qr,updateProjectConfig:Kr},Symbol.toStringTag,{value:"Module"})),Vr="secrets.json";function Jr(e){return le.join(e,".codeyam",Vr)}function Qr(){return le.join(pn.homedir(),".codeyam",Vr)}async function Vt(e){let t={};try{const r=Qr(),a=await ge.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=Jr(e),a=await ge.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function $o(e,t,r=!0){const a=r?Qr():Jr(e),s=le.dirname(a);await ge.mkdir(s,{recursive:!0}),await ge.writeFile(a,JSON.stringify(t,null,2)+`
|
|
29
|
+
`,"utf-8")}async function jo(e){const t=await Vt(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 Do="/assets/globals-BxkM6Up7.css";function Lo({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=k(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(Z,{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","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"})})})]})})}const Oo=()=>[{rel:"stylesheet",href:Do},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function Fo({request:e,context:t}){try{const r=ie()||process.cwd(),[a,s,o]=await Promise.all([Ke(),Pe(),Vt(r)]);if(!s)throw new Error("Project slug not found");const l=t.analysisQueue?.getState(),d=await Promise.all((l?.jobs||[]).map(async v=>{const S=[];if(v.entityShas&&v.entityShas.length>0){const N=v.entityShas.map(A=>Re(A)),E=await Promise.all(N);S.push(...E.filter(A=>A!==null))}return{...v,entities:S}}));let m=null;if(l?.currentlyExecuting){const v=l.currentlyExecuting,S=[];if(v.entityShas&&v.entityShas.length>0){const N=v.entityShas.map(A=>Re(A)),E=await Promise.all(N);S.push(...E.filter(A=>A!==null))}m={...v,entities:S}}let u=a?.metadata?.currentRun?.currentEntityShas||[];if(u.length===0){const v=a?.metadata?.historicalRuns||[];if(v.length>0){const N=[...v].sort((E,A)=>{const I=E.archivedAt||E.createdAt||"";return(A.archivedAt||A.createdAt||"").localeCompare(I)})[0];if(N){const E=N.analysisCompletedAt||N.createdAt;if(E){const A=new Date(E).getTime(),T=Date.now()-1440*60*1e3;A>T&&(u=N.currentEntityShas||[])}}}}const p=(await Promise.all(u.map(v=>Re(v)))).filter(v=>v!==null),f=[];o.ANTHROPIC_API_KEY&&f.push("ANTHROPIC_API_KEY"),o.GROQ_API_KEY&&f.push("GROQ_API_KEY"),o.OPENAI_API_KEY&&f.push("OPENAI_API_KEY"),o.OPENROUTER_API_KEY&&f.push("OPENROUTER_API_KEY");const{project:g,branch:y}=await Ee(s),b=await Ot({projectId:g.id,branchId:y.id,limit:20}),w=[];for(const v of b){const S=v.metadata?.historicalRuns||[];for(const N of S){const E=N.currentEntityShas||[];if(E.length>0){const A=E.map(M=>Re(M)),T=(await Promise.all(A)).filter(M=>M!==null);w.push({...N,entities:T})}else w.push(N)}}const x=w.sort((v,S)=>{const N=v.archivedAt||v.analysisCompletedAt||v.createdAt||"";return(S.archivedAt||S.analysisCompletedAt||S.createdAt||"").localeCompare(N)}),C={currentRun:a?.metadata?.currentRun,projectSlug:s,currentEntities:p,availableAPIKeys:f,queuedJobCount:d.length,queueJobs:d,currentlyExecuting:m,historicalRuns:x};return D(C)}catch(r){return console.error("Failed to load root data:",r),D({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[]})}}function Yo(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l}=Ie(),{toasts:d,closeToast:m}=_n(),u=nt(),h=pe(u),p=br();G(()=>{h.current=u},[u]);const f=p.pathname.startsWith("/entity/")&&p.pathname.includes("/edit/")||p.pathname.startsWith("/dev/");return G(()=>{const g=new EventSource("/api/events");let y=null,b=0;const w=2e3;return g.addEventListener("message",x=>{if(JSON.parse(x.data).type==="db-change"){const v=Date.now(),S=v-b;S<w?(y&&clearTimeout(y),y=setTimeout(()=>{h.current.revalidate(),b=Date.now(),y=null},w-S)):(h.current.revalidate(),b=v)}}),g.addEventListener("error",x=>{console.error("SSE connection error:",x)}),()=>{y&&clearTimeout(y),g.close()}},[]),c(re,{children:[c("div",{className:`min-h-screen ${f?"":"grid"} bg-cygray-10`,style:f?void 0:{gridTemplateColumns:"96px minmax(900px, 1fr)"},children:[!f&&n(vs,{}),c("div",{className:"max-h-screen overflow-auto bg-white",children:[a.length===0&&n(Lo,{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"}),n(Ca,{})]})]}),n(Ss,{toasts:d,onClose:m}),n(As,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const zo=_e(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(xa,{}),n(ba,{})]}),c("body",{children:[n(Cs,{children:n(Yo,{})}),n(wa,{}),n(va,{})]})]})}),Bo=Object.freeze(Object.defineProperty({__proto__:null,default:zo,links:Oo,loader:Fo},Symbol.toStringTag,{value:"Module"})),Zr=vr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),In=()=>{const e=Cr(Zr);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Jt=({children:e})=>{const[t,r]=k({height:720,width:1200}),[a,s]=k(1),[o,i]=k(1200),l=pe(null),d=V(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),m=V(h=>{s(h)},[]),u=V(h=>{i(h)},[]);return n(Zr.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},Uo=ns,qo=typeof window<"u",Wo=1200,Go=720,Zn=30,Ho=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const[m,u]=k(!1),[h,p]=k(!1),[f,g]=k(Wo),[y,b]=k(Go),[w,x]=k(null),[C,v]=k(null),{dimensions:S,updateDimensions:N,iframeRef:E,updateScale:A,updateMaxWidth:I}=In(),T=ee(()=>Math.min(1,f/S.width),[f,S.width]),M=C!==null?C:T;G(()=>{m||(A(M),l?.(M))},[M,A,l,m]),G(()=>{I(f)},[f,I]);const P=V(()=>{u(!0),v(T)},[T]),L=V(()=>{u(!1),v(null)},[]),_=V((F,q)=>{const K=C!==null?C:1,$=Math.round(q.size.width/K);N({width:$}),d?.($,S.height)},[N,C,d,S.height]),R=V(()=>{setTimeout(()=>{p(!0)},100),i&&i()},[i]);G(()=>{const F=q=>{if(q.data.type==="codeyam-resize"){if(t&&q.data.name!==t||S.height===q.data.height||q.data.height===0)return;N({height:q.data.height})}};return window.addEventListener("message",F),()=>{window.removeEventListener("message",F)}},[E,t,a,S,N]),G(()=>{h&&o&&o(E.current)},[h,o,E]),G(()=>{if(!t)return;const F=setInterval(()=>{E?.current?.contentWindow?.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(F)},[t,E]),G(()=>{const F=()=>{const q=document.getElementById("scenario-container");if(!q)return;const K=q.getBoundingClientRect(),$=q.clientWidth-Zn*2,U=window.innerHeight-K.top-Zn*2,j=Math.max(U,400),B=window.innerHeight-K.top;g($),b(j),x(B)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),G(()=>{N({width:a,height:s})},[a,s,N]);const O=ee(()=>S.width*M,[S.width,M]),Y=ee(()=>{const F=S.height,q=F*M;return F&&F!==720&&F!==900&&q<y?q:y},[S.height,y,M]),J=V(()=>{window.history.back()},[]);return qo?c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:w?{height:`${w}px`}:{},children:[m&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
30
|
+
.react-resizable-handle-e {
|
|
31
|
+
display: flex !important;
|
|
32
|
+
align-items: center !important;
|
|
33
|
+
justify-content: center !important;
|
|
34
|
+
width: 6px !important;
|
|
35
|
+
height: 48px !important;
|
|
36
|
+
right: -8px !important;
|
|
37
|
+
top: 50% !important;
|
|
38
|
+
transform: translateY(-50%) !important;
|
|
39
|
+
cursor: ew-resize !important;
|
|
40
|
+
background: #d1d5db !important;
|
|
41
|
+
border-radius: 3px !important;
|
|
42
|
+
opacity: 0 !important;
|
|
43
|
+
transition: all 0.2s ease !important;
|
|
44
|
+
}
|
|
45
|
+
.react-resizable-handle-e:hover {
|
|
46
|
+
opacity: 0.8 !important;
|
|
47
|
+
background: #9ca3af !important;
|
|
48
|
+
}
|
|
49
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
50
|
+
opacity: 0.4 !important;
|
|
51
|
+
}
|
|
52
|
+
`}),n(Uo,{width:O,height:Y,minConstraints:[300,200],maxConstraints:[f,y],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:P,onResizeStop:L,onResize:_,children:n("div",{className:"overflow-auto",style:{width:`${O}px`,height:`${Y}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${M})`,transformOrigin:"top left"},children:r?n("iframe",{ref:E,className:"w-full h-full rounded-lg",src:r,onLoad:R,sandbox:"allow-scripts allow-same-origin"}):c("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:J,children:"Go back"})]})})})},`resizable-box-${e}`)]}):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..."})})};function Ko({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[m,u]=k(!1),[h,p]=k(String(r)),[f,g]=k(String(a)),[y,b]=k(!1),[w,x]=k(!1),C=pe(null);G(()=>{y||p(String(r))},[r,y]),G(()=>{w||g(String(a))},[a,w]),G(()=>{const P=L=>{C.current&&!C.current.contains(L.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const v=ee(()=>{const P=e.find(_=>_.width===r&&_.height===a);if(P)return P.name;const L=t.find(_=>_.width===r&&_.height===a);return L?L.name:"Custom"},[e,t,r,a]),S=v==="Custom",N=P=>{o(P.width,P.height),u(!1)},E=P=>{const L=P.target.value;p(L);const _=parseInt(L,10);!isNaN(_)&&_>0&&o(_,a)},A=P=>{const L=P.target.value;g(L);const _=parseInt(L,10);!isNaN(_)&&_>0&&o(r,_)},I=()=>{b(!1);const P=parseInt(h,10);(isNaN(P)||P<=0)&&p(String(r))},T=()=>{x(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&g(String(a))},M=P=>{(P.key==="Enter"||P.key==="Escape")&&P.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:C,children:[c("button",{onClick:()=>u(!m),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:v}),n("svg",{className:`w-4 h-4 transition-transform ${m?"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"})})]}),m&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(re,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(P=>c("button",{onClick:()=>N(P),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${v===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:P.name}),c("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]},P.name))]}),t.length>0&&c(re,{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((P,L)=>P.width-L.width).map(P=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${v===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>N(P),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:P.name}),c("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]}),l&&n("button",{onClick:L=>{L.stopPropagation(),v===P.name&&e.length>0&&o(e[0].width,e[0].height),l(P.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"})})})]},P.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:E,onFocus:()=>b(!0),onBlur:I,onKeyDown:M,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:A,onFocus:()=>x(!0),onBlur:T,onKeyDown:M,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&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),S&&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 on(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 gn(e){return e&&(typeof e=="object"||Array.isArray(e))}function Vo(e){return Array.isArray(e)?e.length:void 0}function Jo(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=gn(t[s]),l=gn(t[o]);return i&&!l?1:!i&&l?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function Qo({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),c("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Zo({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=V(()=>{s&&s(e)},[s,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Xr=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Xr||{});const Xo=({name:e,value:t,options:r,onChange:a})=>{const s=V(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))})},ei=({name:e,value:t,onChange:r})=>{const a=V(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
|
|
53
|
+
bg-gray-300 checked:bg-blue-600
|
|
54
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
55
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
56
|
+
checked:after:translate-x-4`})})};function ti({dataType:e,path:t,value:r,onChange:a}){const s=ee(()=>t[t.length-1],[t]),o=ee(()=>t.join("-"),[t]),i=V(d=>{a(t,d.target.value)},[a,t]),l=V(d=>{a(t,d.target.value)},[a,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(Xo,{name:o,value:r,options:e.split("|"),onChange:i}):e===Xr.BOOLEAN?n(ei,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function ni({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=k(!1),[l,d]=k(""),m=V(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(b=>b.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(b=>b.name===Gt),f=await s(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(b,w)=>{const x=Object.assign({},b);return y(b)&&y(w)&&Object.keys(w).forEach(C=>{y(w[C])?C in b?x[C]=g(b[C],w[C]):Object.assign(x,{[C]:w[C]}):Object.assign(x,{[C]:w[C]})}),x},y=b=>b&&typeof b=="object"&&!Array.isArray(b);h.metadata.data=g(g(p?.metadata.data||{},h.metadata.data),f.data||{}),a(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,a,s]),u=V(h=>{d(h.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:o?c(re,{children:[c("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function ri({namedPath:e,path:t,last:r,onClick:a}){const s=V(()=>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 ai({dataItem:e,onClick:t}){const r=V(()=>t([]),[t]),a=ee(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>c("div",{className:"flex items-center gap-1",children:[n(ri,{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 Xn({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=ee(()=>r.data,[r]),m=ee(()=>Jo(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(ai,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(ni,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m?.map((u,h)=>{if(gn(d[u])){let f=u;isNaN(Number(u))||(f=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],y=[...r.namedPath,f];return n(Zo,{path:g,namedPath:y,isArray:Array.isArray(d),count:Vo(d[u]),onClick:a},`data-${u}-${h}`)}if(u==="id")return null;const p=[...r.path,u];return n(ti,{dataType:r.structure?.[u]??"string",path:p,value:d[u],onChange:s},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l?.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l?.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l?.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),l?.message&&!l?.isSaving&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function er({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=k(r),l=[];return a&&l.push("border-t"),s&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const si=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:m})=>{const u=V((E,A)=>{const I=Object.assign({},E),T=M=>M&&typeof M=="object"&&!Array.isArray(M);return T(E)&&T(A)&&Object.keys(A).forEach(M=>{T(A[M])?M in E?I[M]=u(E[M],A[M]):Object.assign(I,{[M]:A[M]}):Object.assign(I,{[M]:A[M]})}),I},[]),[h,p]=k({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=k(null),y=ee(()=>({...h.data}),[h]),b=ee(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),w=ee(()=>{const E={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(E).reduce((A,I)=>{if(I.includes(".")){const[T,M]=I.split(".");A[T]||(A[T]={}),A[T][M]=E[I]}else A[I]=E[I];return A},{})},[r]),x=V(async E=>{E.preventDefault();const I=E.target.querySelector('input[name="recapture"]')?.value==="true",T={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:I,dataToSave:T,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(T,null,2).substring(0,1e3));const M=a?.scenarios.map(P=>!s&&P.name===e.name?{...P,name:h.name,description:h.description,metadata:{...P.metadata,data:T}}:P);s&&M.push({name:h.name,description:h.description,metadata:{data:T,interactiveExamplePath:a?.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",M),o&&await o(M,{recapture:I}),i&&i(h.name)},[a,e.name,h,y,s,o,i]),C=V(E=>{p(A=>({...A,[E.target.name]:E.target.value}))},[]),v=V(E=>{g(A=>{if(!A)return null;for(const I of[{arguments:E.metadata.data.argumentsData},E.metadata.data.mockData]){let T=I;for(const M of A.path)if(T=on(T,M),!T)break;T&&(A.data=T)}return{...A}}),p({name:E.name,description:E.description,data:E.metadata.data})},[]),S=V((E,A)=>{p(I=>{for(const T of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let M=T;for(const P of E.slice(0,-1))if(M=on(M,P),!M)break;if(M){const P=M[E[E.length-1]];g(L=>L?(L.namedPath[L.namedPath.length-1]===P&&(L.namedPath[L.namedPath.length-1]=A.toString()),L.data[E[E.length-1]]=A,{...L}):null),M[E[E.length-1]]=A}}return{...I}})},[]),N=V(E=>{if(E.length===0){g(null);return}let A=b;const I=[];let T=w;for(const M of E){if(I.push(isNaN(parseInt(M))?M:A[M]?.name??A[M]?.title??A[M]?.id??M),A=on(A,M),!A){console.log("Data not found",A,M),g(null);return}Array.isArray(T)?T=T[0]:T=T[M]}g({path:E,namedPath:I,data:A,structure:T})},[b,w]);return G(()=>{const E=A=>{A.data.type==="codeyam-log"&&A.data.data?.includes("Error")&&console.error("[ScenarioEditor] Error from iframe:",A.data.data)};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),G(()=>{if(l?.current?.contentWindow){const E={arguments:y.argumentsData??[],...y.mockData??{}},A={type:"codeyam-override-data",name:e.name,data:JSON.stringify(E)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:A.type,name:A.name,dataPreview:JSON.stringify(E).substring(0,200)+"...",fullData:E}),l.current.contentWindow.postMessage(A,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:E=>void x(E),children:f?n(Xn,{analysis:a,scenarioName:h.name,dataItem:f,onClick:N,onChange:S,onAIResult:v,onGenerateData:d,saveFeedback:m}):c(re,{children:[n(er,{title:"Edit Name and Description",borderT:!0,children:n(Qo,{scenarioFormData:h,handleInputChange:C})}),e.metadata.data&&n(er,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Xn,{analysis:a,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:b,structure:w},onClick:N,onChange:S,onAIResult:v,onGenerateData:d,saveFeedback:m})})]})})};function tr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function Rn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0}){const o=fe(),[i,l]=k(null),[d,m]=k(!1),[u,h]=k(!1),[p,f]=k(!1),g=pe(!1),y=pe(null),b=pe(null),[w,x]=k(0),[C,v]=k(0),S=pe(null),N=pe(!1),{interactiveUrl:E,resetLogs:A}=Ye(a,s),I=pe(t);G(()=>{if(I.current!==t&&(I.current=t,y.current&&b.current&&r)){const M=tr(b.current),P=tr(r),L=y.current.replace(M,P);l(L),h(!0),f(!1),x(0),v(_=>_+1),N.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r]),G(()=>{if(E){const M=E+"?width=600px";y.current=M,r&&(b.current=r),l(M),m(!1),h(!0)}},[E]),G(()=>{const M=P=>{P.data.type==="codeyam-resize"&&(N.current||(N.current=!0,S.current&&(clearTimeout(S.current),S.current=null),x(0),f(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h(!1)})})))};return window.addEventListener("message",M),()=>window.removeEventListener("message",M)},[]);const T=()=>{N.current=!1,S.current&&clearTimeout(S.current);const M=500*Math.pow(2,w);S.current=setTimeout(()=>{N.current||(w<2?(x(P=>P+1),v(P=>P+1),h(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),f(!0),h(!1)))},M)};return G(()=>{s&&!g.current&&t&&e&&(g.current=!0,m(!0),f(!1),l(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(P){console.error("[useInteractiveMode] Failed to clear log file:",P)}A(),o.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,A,a]),G(()=>{const M=e,P=()=>{if(g.current&&M){const _=new URLSearchParams({action:"stop",analysisId:M});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const R=navigator.sendBeacon("/api/interactive-mode",_);console.log("[useInteractiveMode] sendBeacon result:",R),R||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:_,keepalive:!0}).catch(O=>console.error("Failed to stop interactive mode:",O)))}},L=()=>{P()};return window.addEventListener("beforeunload",L),()=>{window.removeEventListener("beforeunload",L),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:M}),P()}},[e]),{interactiveServerUrl:i,isStarting:d,isLoading:u,showIframe:p,iframeKey:C,onIframeLoad:T}}function $n({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=Ye(u??null,a||s);return r?c("div",{className:"flex-1 min-h-0 relative",children:[n("div",{style:{opacity:o?1:0},children:n(Ho,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:m},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center gap-3",children:[n("div",{className:"w-12 h-12",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"})})}),c("div",{className:"text-center",children:[n("p",{className:"text-base font-semibold text-[#005c75] mb-1",children:a&&!r?"Starting interactive mode...":`Checking server stability. Attempt #${f+1}..`}),g&&!r&&n("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:g}),r&&f>0&&c("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:["Waiting for application to initialize... (attempt"," ",f+1,")"]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:s?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),g&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:g}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:s?"Loading the page in the background...":"Setting up the dev server for this scenario..."})]})})}const oi=({data:e})=>[{title:e?.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function ii({params:e}){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 Kt(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=s.scenarios?.find(d=>d.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=s.scenarios?.find(d=>d.name===Gt),l=await Pe();return D({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function li(){const e=Ie(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=tt(),{iframeRef:l}=In(),[d,m]=k(!1),[u,h]=k(null),[p,f]=k(null),[g,y]=k(!1),[b,w]=k(!1),[x,C]=k(null),{interactiveServerUrl:v,isStarting:S,isLoading:N,showIframe:E,iframeKey:A,onIframeLoad:I}=Rn({analysisId:t?.id,scenarioId:r?.id,scenarioName:r?.name,projectSlug:o,enabled:!0}),T=V(async(_,R)=>{m(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",R),console.log("[EditScenario] Scenarios to save:",_);try{const O={analysis:t,scenarios:_};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:_.length,scenarioNames:_.map(F=>F.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)}),J=await Y.json();if(console.log("[EditScenario] API response:",J),!Y.ok||!J.success)throw new Error(J.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),R?.recapture&&r.id&&v){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:v}),h("Changes saved. Capturing screenshot...");const F={serverUrl:v,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",F);const q=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});console.log("[EditScenario] Capture response status:",q.status);const K=await q.json();if(console.log("[EditScenario] Capture response body:",K),!q.ok||!K.success)throw console.error("[EditScenario] Capture failed:",K),new Error(K.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",K),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(R?.recapture&&!v){console.log("[EditScenario] No running server, using queued recapture");const F=new FormData;F.append("analysisId",t.id||""),F.append("scenarioId",r.id||"");const q=await fetch("/api/recapture-scenario",{method:"POST",body:F}),K=await q.json();if(!q.ok||!K.success)throw new Error(K.error||"Failed to trigger recapture");console.log("Recapture queued:",K),f(K.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(O){console.error("Error saving scenarios:",O),h(`Error: ${O instanceof Error?O.message:String(O)}`)}finally{m(!1)}},[t,r.id,v]),M=V(_=>{},[]),P=V(async(_,R)=>{const O=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,existingScenarios:t.scenarios,scenariosDataStructure:t.metadata?.scenariosDataStructure,editingMockName:r.name,editingMockData:R?.data})}),Y=await O.json();if(!O.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),L=V(async()=>{if(!r.id){C("Cannot delete scenario without ID");return}y(!0),C(null);try{const _=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:r.metadata?.screenshotPaths||[]})}),R=await _.json();if(!_.ok||!R.success)throw new Error(R.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(_){console.error("[EditScenario] Error deleting scenario:",_),C(_ instanceof Error?_.message:"Failed to delete scenario"),w(!1)}finally{y(!1)}},[r.id,r.metadata?.screenshotPaths,s,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(Z,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",t.entity?.name]})}),c("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(si,{currentScenario:r,defaultScenario:a,dataStructure:t.metadata?.scenariosDataStructure||{},analysis:t,shouldCreateNewScenario:!1,onSave:T,onNavigate:M,iframeRef:l,onGenerateData:P,saveFeedback:{isSaving:d,message:u,isError:u?.startsWith("Error")??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(Z,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),b?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void L(),disabled:g,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:g?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>w(!1),disabled:g,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>w(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),x&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:x})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n($n,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:v,isStarting:S,isLoading:N,showIframe:E,iframeKey:A,onIframeLoad:I,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const ci=_e(function(){return n(Jt,{children:n(li,{})})}),di=Object.freeze(Object.defineProperty({__proto__:null,default:ci,loader:ii,meta:oi},Symbol.toStringTag,{value:"Module"})),ui=({data:e})=>[{title:e?.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function mi({params:e}){const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Kt(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=a.scenarios?.find(i=>i.name===Gt);if(!s)throw new Response("Default scenario not found",{status:404});const o=await Pe();return D({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function hi(){const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Ie(),o=tt(),{iframeRef:i}=In(),[l,d]=k(""),[m,u]=k(!1),[h,p]=k(!1),[f,g]=k(null),[y,b]=k(null),{interactiveServerUrl:w,isStarting:x,isLoading:C,showIframe:v,iframeKey:S,onIframeLoad:N}=Rn({analysisId:e?.id,scenarioId:t?.id,scenarioName:t?.name,projectSlug:s,enabled:!0}),E=V(async()=>{if(!l.trim()){g("Please describe how you want to change the scenario");return}u(!0),g(null),b("Generating scenario with AI...");try{const I=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:e.metadata?.scenariosDataStructure})}),T=await I.json();if(!I.ok||!T.success)throw new Error(T.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",T.data);const M=T.data;if(!M.name||!M.data)throw new Error("AI response missing required fields (name or data)");b("Saving new scenario..."),p(!0);const P={name:M.name,description:M.description||l,metadata:{data:M.data,interactiveExamplePath:t.metadata?.interactiveExamplePath}},L=[...e.scenarios||[],P],_=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:L})}),R=await _.json();if(!_.ok||!R.success)throw new Error(R.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",R);const O=R.analysis?.scenarios?.find(Y=>Y.name===M.name);if(!O?.id){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),b("Scenario created! Redirecting..."),setTimeout(()=>o(`/entity/${a}`),1e3);return}if(w){b("Capturing screenshot...");const Y=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:w,scenarioId:O.id,projectId:e.projectId,viewportWidth:1440})}),J=await Y.json();!Y.ok||!J.success?(console.error("[CreateScenario] Capture failed:",J),b("Scenario created! (Screenshot capture failed)")):b("Scenario created and captured!")}else b("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${O.id}`)},1e3)}catch(I){console.error("[CreateScenario] Error:",I),g(I instanceof Error?I.message:String(I)),b(null)}finally{u(!1),p(!1)}},[l,e,t,a,w,o]),A=m||h;return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(Z,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",r?.name]})}),n("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:"Create New Scenario"}),n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:"Create a new scenario based on the Default Scenario"})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Describe how you'd like to change it to create your new scenario."})]}),c("div",{className:"flex-1",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"How would you like to change it for your new scenario?"}),n("textarea",{id:"prompt",value:l,onChange:I=>d(I.target.value),placeholder:"e.g., Show an empty state with no items in the list, or Display an error message when the API fails, or Show a user with admin privileges...",className:"w-full h-40 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:A})]}),c("div",{className:"mt-6 space-y-3",children:[n("button",{onClick:()=>void E(),disabled:A||!l.trim(),className:"w-full px-4 py-2 bg-[#005c75] text-white rounded-md text-sm font-medium hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors",children:A?"Creating...":"Create Scenario"}),y&&n("div",{className:"text-sm text-blue-600 bg-blue-50 px-3 py-2 rounded-md",children:y}),f&&n("div",{className:"text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:f})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n($n,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:w,isStarting:x,isLoading:C,showIframe:v,iframeKey:S,onIframeLoad:N,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const pi=_e(function(){return n(Jt,{children:n(hi,{})})}),fi=Object.freeze(Object.defineProperty({__proto__:null,default:pi,loader:mi,meta:ui},Symbol.toStringTag,{value:"Module"}));var H;(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={}))})(H||(H={}));function ea(e,t){return e?Object.values(H.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const ta=ea(process.env.DEFAULT_SMALLER_MODEL,H.Model.OPENAI_GPT4_1_MINI),gi=ea(process.env.DEFAULT_LARGER_MODEL,H.Model.OPENAI_GPT4_1),ke={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},ln={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},yi={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},cn={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Oe={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},xi={[H.Model.OPENAI_GPT5_1]:{id:H.Model.OPENAI_GPT5_1,provider:ke,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[H.Model.OPENAI_GPT5]:{id:H.Model.OPENAI_GPT5,provider:ke,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[H.Model.OPENAI_GPT5_MINI]:{id:H.Model.OPENAI_GPT5_MINI,provider:ke,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[H.Model.OPENAI_GPT5_NANO]:{id:H.Model.OPENAI_GPT5_NANO,provider:ke,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[H.Model.OPENAI_GPT4_1]:{id:H.Model.OPENAI_GPT4_1,provider:ke,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[H.Model.OPENAI_GPT4_1_MINI]:{id:H.Model.OPENAI_GPT4_1_MINI,provider:ke,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[H.Model.OPENAI_GPT4_O]:{id:H.Model.OPENAI_GPT4_O,provider:ke,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[H.Model.OPENAI_GPT4_O_MINI]:{id:H.Model.OPENAI_GPT4_O_MINI,provider:ke,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[H.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:H.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:ln,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[H.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:H.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:ln,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[H.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:H.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:ln,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[H.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:H.Model.OPENAI_GPT_OSS_120B_GROQ,provider:yi,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[H.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:H.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Oe,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[H.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:H.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Oe,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[H.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:H.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Oe,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[H.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:H.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Oe,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[H.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:H.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Oe,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[H.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:H.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:cn,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[H.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:H.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:cn,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[H.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:H.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:cn,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[H.Model.PHIND_CODELLAMA]:{id:H.Model.PHIND_CODELLAMA,provider:ke,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[H.Model.GOOGLE_GEMINI_PRO]:{id:H.Model.GOOGLE_GEMINI_PRO,provider:Oe,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[H.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:H.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Oe,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[H.Model.META_CODELLAMA_34B_INSTRUCT]:{id:H.Model.META_CODELLAMA_34B_INSTRUCT,provider:Oe,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[H.Model.OPENAI_GPT4_PREVIEW]:{id:H.Model.OPENAI_GPT4_PREVIEW,provider:ke,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Qt(e){const t=xi[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function bi(e){return Qt(e).maxCompletionTokens}function wi(e){return Qt(e).pricing}const nr=1e6;function vi({model:e,usage:t}){const r=wi(e);return r?t.prompt_tokens*(r.input/nr)+t.completion_tokens*(r.output/nr):null}function Ci({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=vi({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 Ni({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??ta,i=Qt(o);bi(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format: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}}}An(Nn);const At=new as({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),rr={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Et={};async function yn({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=ta,attempts:i=0}){if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Si(e,process.env.CODEYAM_LLM_FIXTURES_DIR);console.log(`CodeYam Debug: LLM Pool [queued=${At.size}, running=${At.pending}]`);const l=Date.now();let d,m=0;const u=Qt(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)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 p=new rs({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},g=Ni(f),y=await At.add(()=>(d=Date.now(),Hn(()=>p.chat.completions.create(g,{timeout:300*1e3}),{...rr,onFailedAttempt:N=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:N,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})),{throwOnTimeout:!0}),b=Date.now(),w=Ci({chatRequest:f,chatCompletion:y,model:o});if(!w)throw new Error("Failed to get LLM call stats");w.retries=m,w.wait_ms=d-l,w.duration_ms=b-l;const x=y.choices?.[0];let C=null;if(x){if(!x.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:y,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");C=x.message?.content}let v=C;C&&(v=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const S=a?v&&(v.match(/\{[\s\S]*\}/)?.[0]??v):v;if(!S){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:S,rawCompletion:C,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await yn({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(S.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(S)}catch(N){if(console.log("CodeYam Error: Invalid JSON in completion",{error:N.message,model:o,completion:S.substring(0,500),rawCompletion:C?.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:N.message});const E=`Your previous response contained invalid JSON with the following error:
|
|
57
|
+
|
|
58
|
+
${N.message}
|
|
59
|
+
|
|
60
|
+
Here was your previous response:
|
|
61
|
+
\`\`\`
|
|
62
|
+
${S}
|
|
63
|
+
\`\`\`
|
|
64
|
+
|
|
65
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,A=await At.add(()=>Hn(()=>p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:S},{role:"user",content:E}]},{timeout:300*1e3}),{...rr,onFailedAttempt:P=>{console.log("CodeYam Error: Correction call failed",{error:P,attempts:i})}}),{throwOnTimeout:!0}),I=A.choices?.[0]?.message?.content;let T=I;I&&(T=I.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const M=T&&(T.match(/\{[\s\S]*\}/)?.[0]??T);if(!M)throw new Error("Correction attempt returned empty completion");try{JSON.parse(M),console.log("CodeYam: JSON correction successful");const P=Date.now();return w.duration_ms=P-l,{finishReason:A.choices[0].finish_reason,completion:M,stats:w}}catch(P){return console.log("CodeYam Error: Corrected JSON still invalid",{error:P.message,correctedCompletion:M.substring(0,500)}),await yn({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${N.message}`)}return{finishReason:y.choices[0].finish_reason,completion:S,stats:w}}async function Si(e,t){const r=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!r.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 s=r.readdirSync(t).filter(h=>h.endsWith(".json"));if(s.length===0)throw new Error(`No LLM fixture files found in ${t}`);const o={};for(const h of s)try{const p=r.readFileSync(a.join(t,h),"utf-8"),f=JSON.parse(p);o[f.prompt_type]||(o[f.prompt_type]=[]),o[f.prompt_type].push(f)}catch(p){console.warn(`Failed to parse LLM fixture file ${h}:`,p)}const i=o[e];if(!i||i.length===0){const h=Object.keys(o).join(", ");throw new Error(`No captured LLM call found for type '${e}'. Available types: ${h}`)}const l=`${t}::${e}`;Et[l]||(Et[l]=0);const d=Et[l];Et[l]=(d+1)%i.length;const m=i[d];console.log(`CodeYam Test: Replaying LLM response for '${e}' [${d+1}/${i.length}]`);let u;try{u=JSON.parse(m.response).choices?.[0]?.message?.content||m.response}catch{u=m.response}return{finishReason:"stop",completion:u,stats:{model:m.model??"fixture",prompt_type:e,system_message:m.system_message??"",prompt_text:m.prompt_text??"",response:m.response??"",input_tokens:m.input_tokens??0,output_tokens:m.output_tokens??0,cost:m.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(s){throw console.error("CodeYam Test Error: Failed to replay LLM call:",s),s}}function ar(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Ai(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=gt(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let l;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?l=ae.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=ae.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const u=ae.dirname(l);return await ve.mkdir(u,{recursive:!0}),await ve.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=ar();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new Wt().send(new ss({TableName:ar(),Item:is(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new Wt({});new Wt({});new Wt({});const Ei=3,_i=2,jn=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Ei*String(t).length*(1+_i)});new En(jn());new En(jn());new En(jn());class Pi{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){return this.byClassAndMethod.get(t)?.get(r)}}class Mi{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 Ti{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 ki{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 Ii{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addType(t,"array"),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Ri{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.withReturnValues();a.addType(s,"array")}isComplete(){return!0}}class $i{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 ji{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 Di{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 Li{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 Oi{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Fi{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 Yi{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 zi{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 Bi{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Ui{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 qi(){const e=new Pi;return e.register("filter",new Mi,"Array"),e.register("map",new Di,"Array"),e.register("flatMap",new Li,"Array"),e.register("join",new ji,"Array"),e.register("find",new Ti,"Array"),e.register("findLast",new Fi,"Array"),e.register("at",new Oi,"Array"),e.register("reduce",new ki,"Array"),e.register("concat",new Ii,"Array"),e.register("slice",new Ri,"Array"),e.register("splice",new $i,"Array"),e.register("fromEntries",new Yi,"Object"),e.register("then",new zi,"Promise"),e.register("useState",new Ui,"React"),e.register("useMemo",new Bi,"React"),e}qi();class Wi{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 Wi({enabled:!1});const Gi=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Hi=new Set(["find","at","pop","shift"]),Ki=new Set(["map","reduce","flatMap","concat","join","some"]),Vi=new Set([...Gi,...Hi,...Ki]),Ji=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Qi=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Zi=new Set([...Ji,...Qi]);[...Vi,...Zi];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"));function na(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 os.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),na(e)}return null}}function Xi({description:e,existingScenarios:t,scenariosDataStructure:r}){return`Mock Scenario Data Structure:
|
|
66
|
+
\`\`\`
|
|
67
|
+
${JSON.stringify(r,null,2)}
|
|
68
|
+
\`\` Existing Mock Scenario Data:
|
|
69
|
+
\`\`\`
|
|
70
|
+
${JSON.stringify(t,null,2)}
|
|
71
|
+
\`\`\`
|
|
72
|
+
New Scenario user-created prompt: "${e}"
|
|
73
|
+
`}function el({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===Gt);return`Mock Scenario Data Structure:
|
|
74
|
+
\`\`\`
|
|
75
|
+
${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
|
|
76
|
+
\`\`\`
|
|
77
|
+
|
|
78
|
+
Existing Mock Scenario Data:
|
|
79
|
+
\`\`\`
|
|
80
|
+
${JSON.stringify(a.map(i=>({name:i.name,data:fn(o.metadata.data,i.metadata.data)})),null,2)}
|
|
81
|
+
\`\`\`
|
|
82
|
+
|
|
83
|
+
Mock Scenario that should be edited: "${t}"
|
|
84
|
+
${r?`The portion of the data that should be edited:
|
|
85
|
+
\`\`\`
|
|
86
|
+
${JSON.stringify(r,null,2)}
|
|
87
|
+
\`\`\``:""}
|
|
88
|
+
|
|
89
|
+
How this data should be changed: "${e}"
|
|
90
|
+
`}async function tl({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:o}){const i=t?el({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):Xi({description:e,existingScenarios:a,scenariosDataStructure:s}),l=await yn({type:"guessScenarioDataFromDescription",systemMessage:t?rl(r):nl,prompt:i,model:o??gi});await Ai({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:o},...l.stats});const{completion:d}=l;return d?na(d):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const nl=`
|
|
91
|
+
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.
|
|
92
|
+
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
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.
|
|
96
|
+
|
|
97
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
98
|
+
\`\`\`
|
|
99
|
+
export type ScenarioData = {
|
|
100
|
+
name: string;
|
|
101
|
+
description: string;
|
|
102
|
+
data: {
|
|
103
|
+
mockData: { [key: string]: unknown };
|
|
104
|
+
argumentsData: { [key: string]: unknown };
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
\`\`\`
|
|
109
|
+
`,rl=e=>`
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
113
|
+
${e?`
|
|
114
|
+
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.`:""}
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
You must respond with valid JSON following this type definition:
|
|
119
|
+
\`\`\`
|
|
120
|
+
{
|
|
121
|
+
data: {
|
|
122
|
+
mockData: { [key: string]: unknown };
|
|
123
|
+
argumentsData: { [key: string]: unknown };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
\`\`\`
|
|
127
|
+
`;async function al({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i}=t;if(!r)return D({error:"Missing required field: description"},{status:400});const l=await tl({description:r,existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i});return D({success:!0,data:l})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),D({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const sl=Object.freeze(Object.defineProperty({__proto__:null,action:al},Symbol.toStringTag,{value:"Module"}));async function ol(e,t){const r=ie();if(!r)return{entityCalls:[],analysisCalls:[]};const a=ae.join(r,".codeyam","llm-calls");try{await ve.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const l=(await ve.readdir(a)).filter(w=>w.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],h=[];for(const w of l)w.startsWith(d)||m&&w.startsWith(m)?u.push(w):h.push(w);const p=u.map(async w=>{try{const x=ae.join(a,w),C=await ve.readFile(x,"utf-8");return JSON.parse(C)}catch{return null}}),f=h.map(async w=>{try{const x=ae.join(a,w),C=await ve.readFile(x,"utf-8"),v=JSON.parse(C);return v.object_id===e||t&&v.object_id===t?v:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),b=[...g,...y].filter(w=>w!==null);for(const w of b)w.object_id===e?s.push(w):t&&w.object_id===t&&o.push(w);s.sort((w,x)=>x.created_at-w.created_at),o.sort((w,x)=>x.created_at-w.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function il({params:e,request:t}){const{entitySha:r}=e;if(!r)return D({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await ol(r,s);return D(o)}const ll=Object.freeze(Object.defineProperty({__proto__:null,loader:il},Symbol.toStringTag,{value:"Module"}));function cl(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ae("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return dl(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function dl(e){const t=e.trim().split(`
|
|
128
|
+
`).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]+/,""),l,d=!1,m;if(s==="A"||o==="A")l="added",d=s==="A";else if(s==="M"||o==="M")l="modified",d=s==="M";else if(s==="D"||o==="D")l="deleted",d=s==="D";else if(s==="R"||o==="R"){l="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=le.join(u,i);try{const p=(g,y)=>{const b=qe.readdirSync(g,{withFileTypes:!0}),w=[];for(const x of b){const C=le.join(g,x.name),v=le.relative(u,C);x.isDirectory()?w.push(...p(C,y)):x.isFile()&&w.push(v)}return w},f=p(h,u);for(const g of f)r.push({path:g,status:l,staged:d,...m&&{oldPath:m}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...m&&{oldPath:m}})}return r}function ul(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae("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 ml(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Ae('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 Ae("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ae("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 hl(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
129
|
+
`).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function ra(){const e=ie();return e?cl(e):[]}function pl(){const e=ie();return e?ul(e):null}function fl(){const e=ie();return e?ml(e):"main"}function gl(){const e=ie();return e?hl(e):[]}function aa(e,t){const r=ie();return r?yl(e,t,r):[]}function yl(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
130
|
+
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let m=l[1],u,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",u=l[1],m=l[2]):h="modified",{path:m,status:h,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function xl(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Ae(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=qe.readFileSync(le.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 bl(e){const t=ie();return t?xl(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function wl(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Ae(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Ae(`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 It(e,t,r){const a=ie();return a?wl(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function sr(e,t){try{return Ae(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]})?.toString()?.trim()??null}catch(r){return console.error(`Failed to get commit SHA for ${e}:`,r),""}}function vl(e,t,r,a){const s=Cn.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function sa(){const e=ie();if(!e)throw new Error("No project root found");const t=le.join(e,".codeyam","cache","branch-entity-diff");return qe.existsSync(t)||qe.mkdirSync(t,{recursive:!0}),t}function Cl(e){try{const t=sa(),r=le.join(t,`${e}.json`);if(!qe.existsSync(r))return null;const a=qe.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Nl(e,t){try{const r=sa(),a=le.join(r,`${e}.json`);qe.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Sl(e,t,r){const a=Lt(t,e),s=Lt(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),l=[],d=[],m=[];for(const[u,h]of i){const p=o.get(u);p?p.sha!==h.sha&&d.push({name:u,baseSha:p.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[u,h]of o)i.has(u)||m.push(h);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:m}}function Al(e,t){const r=ie();if(!r)throw new Error("No project root found");const a=sr(e,r),s=sr(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=vl(e,t,a,s),i=Cl(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=aa(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=It(u.path,e,t),p=Lt(h.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const h=It(u.path,e,t),p=Lt(h.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=It(u.path,e,t),p=Sl(u.path,h.oldContent,h.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const m={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Nl(o,m),m}function El({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return D({error:"Missing required parameters: base and compare"},{status:400});const s=Al(r,a);return D(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),D({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const _l=Object.freeze(Object.defineProperty({__proto__:null,loader:El},Symbol.toStringTag,{value:"Module"}));async function Pl({request:e}){if(e.method!=="POST")return D({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 D({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=ie();if(!i)return D({error:"Project root not found"},{status:500});const l=ae.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),m=await new Promise(p=>{const f=ae.join(i,".codeyam","db.sqlite3"),g=Sn("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",b="";g.stdout.on("data",w=>{const x=w.toString();y+=x;const C=x.trim().split(`
|
|
131
|
+
`);for(const v of C)v.includes("[Capture]")&&console.log(v)}),g.stderr.on("data",w=>{const x=w.toString();b+=x,console.error("[Capture:Error]",x.trim())}),g.on("close",w=>{p(w===0?{success:!0,output:y}:{success:!1,output:y,error:b||`Process exited with code ${w}`})}),g.on("error",w=>{console.error("[Capture] Failed to spawn child process:",w),p({success:!1,output:"",error:w.message})})});if(!m.success)return D({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return D({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return D(h)}catch(t){return console.error("[Capture] Error:",t),D({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ml=Object.freeze(Object.defineProperty({__proto__:null,action:Pl},Symbol.toStringTag,{value:"Module"}));async function Tl(e,t,r){console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await we();const a=await ze({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ce(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i?.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(l)}).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 ${a.scenarios?.length||0} scenarios`),await bt(e,f=>{if(f&&(f.readyToBeCaptured=!0,f.scenarios))for(const g of f.scenarios)delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=ie();if(!d)throw new Error("Project root not found");const m=ae.join(d,".codeyam","config.json"),u=JSON.parse(se.readFileSync(m,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function kl(e,t,r){console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await we();const a=await ze({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=a.scenarios?.find(u=>u.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 bt(e,u=>{if(u&&(u.readyToBeCaptured=!0,u.scenarios)){const h=u.scenarios.find(p=>p.name===s.name);h&&(delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${s.name} for recapture`);const o=ie();if(!o)throw new Error("Project root not found");const i=ae.join(o,".codeyam","config.json"),l=JSON.parse(se.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}function Bt(e){return ae.join(e,".codeyam","queue.json")}function mt(e){const t=Bt(e);if(!se.existsSync(t))return{paused:!1,jobs:[]};try{const r=se.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Il(e,t){const r=Bt(e),a=ae.dirname(r);se.existsSync(a)||se.mkdirSync(a,{recursive:!0});try{se.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function Rl({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){return new Promise((i,l)=>{const d=e.endsWith("/")?e:`${e}/`,m=t.endsWith("/")?t:`${t}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...o);for(const f of r)u.push(`--exclude=${f}`);u.push(d,m);const h=Date.now(),p=Sn("rsync",u);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-h)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),l(f)})})}const $l=An(Nn);async function jl(e){return new Promise(t=>setTimeout(t,e))}function Dl(e){try{return process.kill(e,0),!0}catch{return!1}}async function oa(e){try{const{stdout:t}=await $l(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
132
|
+
`).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await oa(s);a.push(...o)}return a}catch{return[]}}function or(e,t,r){try{process.kill(e,t)}catch(a){r?.(`Error sending ${t} to process ${e}: ${a}`)}}async function Ll(e,t,r){const a=await oa(e);for(const s of a.reverse())await or(s,t,r);await or(e,t,r)}async function Ut(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 Ll(e,o,t);for(let l=0;l<i;l++)if(await jl(1e3),a+=1e3,!await Dl(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 Ol(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??=[],e.historicalRuns.push(e.currentRun)),e.currentRun={id:ps(),createdAt:t}}ls.config({quiet:!0});var ia=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ia||{});class Fl extends cs{constructor(){super(...arguments),this.processes=new Map}register(t){const r=us(),{process:a,type:s,name:o,metadata:i,parentId:l}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const m=(h,p)=>{this.handleProcessExit(r,h,p)},u=h=>{this.handleProcessError(r,h)};return a.on("exit",m),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",m),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(l=>this.shutdown(l,r))),o.pid)try{await Ut(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,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 l=o.process.__cleanup;l&&l(),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 dn=null;function Yl(){return dn||(dn=new Fl),dn}const zl={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Bl({command:e,args:t,workingDir:r,outputOptions:a=zl,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},l=Sn(e,t,{cwd:r,env:i});return Yl().register({process:l,type:ia.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const g=le.join(r,"log.txt");se.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
|
|
133
|
+
`).map(w=>w.trim()?`[${y}]${g} ${w}`:w).join(`
|
|
134
|
+
`)};l.stdout.on("data",function(f){const g=f?.toString()??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&h(y+`
|
|
135
|
+
`),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=f?.toString()??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&h(y+`
|
|
136
|
+
`),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function Ul(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 ql({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
137
|
+
`);se.writeFileSync(`${e}/.env`,s);const o=Ul(r);return Bl({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const Wl=ae.dirname(Mr(import.meta.url));function Gl(e){let t=e;for(;t!==ae.dirname(t);){const r=ae.join(t,"package.json");if(se.existsSync(r))try{if(JSON.parse(se.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=ae.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Dn(){const e=Gl(Wl);return ae.join(e,"analyzer-template")}function ot(e){return`/tmp/codeyam/local-dev/${e}/codeyam`}async function ir(e){const t=Dn(),r=ot(e);if(!se.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await ve.mkdir(ae.dirname(r),{recursive:!0}),await Rl({sourcePath:t,destinationPath:r,silent:!0})}function Zt(e,t,r,a){const s=ot(e);if(!se.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 ql({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Hl(e){const t=Dn(),r=ot(e),a=ae.join(t,".build-info.json"),s=ae.join(r,".build-info.json");if(!se.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!se.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!se.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(se.readFileSync(a,"utf8")),i=JSON.parse(se.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 Kl(e,t){const r=ot(e);if(!se.existsSync(r)){t.update("Creating analyzer..."),await ir(e);return}const a=Hl(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await ir(e))}const Vl=ae.dirname(Mr(import.meta.url));function la(){let e=Vl;for(;e!==ae.dirname(e);){const t=ae.join(e,"package.json");if(se.existsSync(t))try{if(JSON.parse(se.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=ae.dirname(e)}return null}function Jl(){const e=la();return e?ae.join(e,"package.json"):null}function Rt(e){if(!se.existsSync(e))return null;try{return JSON.parse(se.readFileSync(e,"utf8"))}catch{return null}}function Ql(e){let t="unknown";const r=la(),a=Jl();if(a)try{t=JSON.parse(se.readFileSync(a,"utf8")).version||"unknown"}catch{}let s=null;if(r){const u=[ae.join(r,"src/webserver/build-info.json"),ae.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const h of u)if(s=Rt(h),s)break}const o=Dn(),i=ae.join(o,".build-info.json"),l=Rt(i);let d=null;if(e){const u=ot(e),h=ae.join(u,".build-info.json");d=Rt(h)}let m=!1;return l&&d?m=l.buildTime>d.buildTime:l&&!d&&e&&(m=!0),{cliVersion:t,webserverVersion:s,templateVersion:l,cachedAnalyzerVersion:d,isCacheStale:m}}function ca(e){const t=ot(e),r=ae.join(t,".build-info.json");return Rt(r)?.version??null}class Zl extends ds{watcher=null;dbPath=null;isWatching=!1;async start(){if(!this.isWatching)try{this.dbPath=st();const{default:t}=await import("chokidar"),r=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=t.watch(r,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const s=Date.now(),o=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${o} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:s})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(t){console.error("Failed to start database watcher:",t),this.emit("error",t)}}notifyChange(t="unknown"){const r=Date.now(),a=new Date(r).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${t}`),console.log(`[dbNotifier] Timestamp: ${a} (${r})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:t,timestamp:r})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Ze=new Zl;async function Xl(e,t){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await ec(e,t);else if(e.type==="recapture")await tc(e,t);else if(e.type==="debug-setup")await nc(e,t);else if(e.type==="interactive-start")await rc(e,t);else if(e.type==="interactive-stop")await ac(e,t);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(r){throw console.error(`[Queue] Job ${e.id} failed:`,r),r}}async function ec(e,t){const{projectSlug:r,commitSha:a,entityShas:s}=e;if(!a)throw new Error("Analysis job missing commitSha");const o=s||[],{project:i}=await Ee(r);await Kl(r,{update:g=>console.log(`[Queue] ${g}`)});const l=ca(r),d={...await at(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:st(),...o.length>0?{ENTITY_SHAS:o.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...l?{ANALYZER_VERSION:l}:{}},m=i.metadata?.webapps?.[0];if(!m)throw new Error("No webapps found in project metadata");const u=e.onlyDataStructure,h={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:0,noServer:!0,framework:m.framework,...u?{}:{orchestrateCapture:"local-sequential"}},p=Zt(r,d,h),f=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Qe({commitSha:a,runStatusUpdate:{currentEntityShas:o,entityCount:o.length||e.filePaths?.length||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:p.process.pid}}),Ze.notifyChange("commit");try{try{const g=new Promise((y,b)=>setTimeout(()=>b(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([p.promise,g]),await Qe({commitSha:a,runStatusUpdate:{analyzerPid:void 0},archiveCurrentRun:!0}),Ze.notifyChange("commit"),await Qe({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),Ze.notifyChange("commit"),await new Promise(y=>setTimeout(y,2e3))}finally{if(p.process.pid)try{f(p.process.pid)&&await Ut(p.process.pid,()=>{})}catch{}}}catch(g){if(console.error(`[Queue] Analysis job ${e.id} failed:`,g),p.process.pid&&f(p.process.pid))try{await Ut(p.process.pid,()=>{})}catch{}try{await Qe({commitSha:a,runStatusUpdate:{analyzerPid:void 0,failedAt:new Date().toISOString(),failureReason:g instanceof Error?g.message:String(g)}}),Ze.notifyChange("commit")}catch(y){console.error("[Queue] Failed to update commit metadata after job failure:",y)}throw g}}async function tc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s,defaultWidth:o}=e;if(!a)throw new Error("Recapture job missing analysisId");const i=await ze({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);if(o){const{getDatabase:p}=await import("./index-Dpr7o3dP.js"),f=p(),g=await f.selectFrom("entities").select(["metadata"]).where("sha","=",i.entitySha).executeTakeFirst();let y={};g?.metadata&&(typeof g.metadata=="string"?y=JSON.parse(g.metadata):y=g.metadata),y.defaultWidth=o,await f.updateTable("entities").set({metadata:JSON.stringify(y)}).where("sha","=",i.entitySha).execute()}await bt(a,p=>{if(p.readyToBeCaptured=!0,p.scenarios)for(const f of p.scenarios)(!s||f.name===s)&&(delete f.screenshotStartedAt,delete f.screenshotFinishedAt,delete f.interactiveStartedAt,delete f.interactiveFinishedAt,delete f.error,delete f.errorStack)});const{project:l}=await Ee(r),d=ca(r),m={...await at(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:st(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...s?{SCENARIO_IDS:s}:{},...d?{ANALYZER_VERSION:d}:{}},u={packageManager:l.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!0,framework:l.metadata?.webapps?.[0]?.framework??xt.Next,orchestrateCapture:"local-sequential"},h=Zt(r,m,u);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function nc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s}=e;if(!a)throw new Error("Debug setup job missing analysisId");const o=await ze({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o||!o.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Ee(r),l={...await at(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:o.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:st(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};s&&(l.SCENARIO_IDS=s);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||xt.Next},u=await Zt(r,l,d).promise;if(u!==0)throw new Error(`Prep process exited with code ${u}`)}async function rc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s}=e;if(!a)throw new Error("Interactive start job missing analysisId");const o=await ze({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o||!o.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Ee(r),l={...await at(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:o.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:st(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};s&&(l.SCENARIO_IDS=s);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||xt.Next};await bt(a,u=>{u.readyToBeCaptured=!0});const m=Zt(r,l,d);await Yr(a,u=>{u.interactiveMode={pid:m.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${m.process.pid}`)}async function ac(e,t){const{projectSlug:r,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const s=await ze({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${a} not found`);const o=s.metadata?.interactiveMode;if(!o?.pid){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const i=o.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${i}`);try{try{process.kill(i,0)}catch{console.log(`[Queue] Process ${i} already exited`);return}await Ut(i,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${i}`)}catch(l){throw console.error(`[Queue] Failed to kill process ${i}:`,l),l}finally{await Yr(a,l=>{l.interactiveMode=null})}}class sc{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},this.onStateChange=r}start(){this.state=mt(this.projectRoot),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||gt(),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,l=>{l?i(l):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)}async processNext(){if(this.state.paused||this.processing||this.state.jobs.length===0)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 Xl(t,this.projectRoot),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`)}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?.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(){Il(this.projectRoot,this.state),this.onStateChange&&this.onStateChange()}}class oc{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=Bt(this.projectRoot);if(!se.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=Bt(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=se.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=se.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 ic{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=mt(r)}start(){this.cachedState=mt(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 oc(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,l)=>{r=i,a=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),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=mt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=mt(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 lc(e){const t=ae.join(e,".codeyam","server.json");if(!se.existsSync(t))return null;try{const r=se.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function cc(e){try{return process.kill(e,0),!0}catch{return!1}}async function dc(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 uc(e){const t=lc(e);return!t||!cc(t.pid)||!await dc(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}let ht=null,_t=null;async function mc(){if(!ht){if(_t){await _t;return}_t=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||zr()||process.cwd();Po(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await uc(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new ic(t,e,()=>{Ze.notifyChange("unknown")});await r.start(),ht=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new sc(e,()=>{Ze.notifyChange("unknown")});await r.start(),ht=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await _t}}async function De(){return ht||await mc(),ht}async function hc({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await De()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return D({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await kl(s,o,r);return console.log("[API] Scenario recapture queued",i),D({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),D({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const pc=Object.freeze(Object.defineProperty({__proto__:null,action:hc},Symbol.toStringTag,{value:"Module"}));async function fc({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=`/tmp/codeyam/local-dev/${r}/codeyam/log.txt`;try{return await Za(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 gc({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=`/tmp/codeyam/local-dev/${t}/codeyam/log.txt`;try{if(!Wa(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 Xa(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 yc=Object.freeze(Object.defineProperty({__proto__:null,action:fc,loader:gc},Symbol.toStringTag,{value:"Module"}));async function xc(e,t){console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await we();const r=await ze({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=r.scenarios?.find(o=>o.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:a.metadata?.data?.argumentsData?.[0]||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify(a.metadata?.data?.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 bc({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return D({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await xc(r,a);return console.log("[API] Function execution completed successfully"),D({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),D({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const wc=Object.freeze(Object.defineProperty({__proto__:null,action:bc},Symbol.toStringTag,{value:"Module"}));function vc({request:e}){return D({status:"ok"})}async function Cc({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await De()),!r)return console.error("[Interactive Mode API] Queue not initialized"),D({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 D({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return D({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Pe();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return D({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return D({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return D({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),D({error:"Failed to control interactive mode",details:s},{status:500})}}const Nc=Object.freeze(Object.defineProperty({__proto__:null,action:Cc,loader:vc},Symbol.toStringTag,{value:"Module"}));async function Sc({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=ie();if(s)for(const o of a){const i=le.join(s,".codeyam","captures","screenshots",o);try{await ge.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}return await to({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 Ac=Object.freeze(Object.defineProperty({__proto__:null,action:Sc},Symbol.toStringTag,{value:"Module"})),lr=An(Nn);async function Ec({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=_c(o),l=i?await Pc(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:s})}function _c(e){try{return process.kill(e,0),!0}catch{return!1}}async function Pc(e){try{const{stdout:t}=await lr(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await lr(`ps -p ${e} -o args=`),a=r.trim(),s=a.match(/codeyam-(\w+)/);return s?`codeyam-${s[1]}`:a.split(" ")[0]||null}catch{return null}}}const Mc=Object.freeze(Object.defineProperty({__proto__:null,loader:Ec},Symbol.toStringTag,{value:"Module"}));async function Tc({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((l,d)=>{const m=l.metadata?.data?.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!l.metadata?.data,mockDataKeys:l.metadata?.data?.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const s=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await bo(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((l,d)=>{const m=l.metadata?.data?.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(m)?m.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 kc=Object.freeze(Object.defineProperty({__proto__:null,action:Tc},Symbol.toStringTag,{value:"Module"}));async function Ic({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(!cr(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,l=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,l)),m=cr(r);if(m){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 Qe({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 cr(e){try{return process.kill(e,0),!0}catch{return!1}}const Rc=Object.freeze(Object.defineProperty({__proto__:null,action:Ic},Symbol.toStringTag,{value:"Module"}));async function $c({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=ie();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=le.join(r,".codeyam","captures","screenshots",t);try{await ge.access(a);const s=await ge.readFile(a),o=le.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 jc=Object.freeze(Object.defineProperty({__proto__:null,loader:$c},Symbol.toStringTag,{value:"Module"}));function Dc(e){const t=Date.now(),r=new Date(e).getTime(),a=t-r,s=Math.floor(a/6e4),o=Math.floor(s/60);return s<1?"just now":s<60?`${s}m ago`:o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Lc({state:e,currentRun:t}){fe();const r=t?.currentEntityShas&&t.currentEntityShas.length>0;return!e.currentlyExecuting&&(!e.jobs||e.jobs.length===0)?null:c("div",{className:"bg-white border-2 rounded-xl shadow-lg p-5 mb-6",style:{borderColor:"#005C75"},children:[e.currentlyExecuting&&!r&&c("div",{className:"mb-4 border-2 rounded-lg p-3",style:{backgroundColor:"#e8f1f5",borderColor:"#005C75"},children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(jt,{size:20,className:"animate-spin",style:{color:"#005C75"}}),n("span",{className:"text-sm font-bold",style:{color:"#003d52"},children:"Starting analysis..."})]}),c("p",{className:"text-xs mb-2",style:{color:"#004a5e"},children:["Booting analyzer for"," ",e.currentlyExecuting.entities?.length||e.currentlyExecuting.entityShas?.length||1," ",(e.currentlyExecuting.entities?.length||e.currentlyExecuting.entityShas?.length)===1?"entity":"entities"]}),e.currentlyExecuting.entities&&e.currentlyExecuting.entities.length>0&&c("div",{className:"space-y-1 mt-2 max-h-[100px] overflow-y-auto bg-white rounded-md p-2 border",style:{borderColor:"#b3d9e6"},children:[e.currentlyExecuting.entities.slice(0,3).map(a=>c(Z,{to:`/entity/${a.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate",title:`${a.name} - ${a.filePath}`,style:{color:"#005C75"},onMouseEnter:s=>s.currentTarget.style.color="#003d52",onMouseLeave:s=>s.currentTarget.style.color="#005C75",children:[n($e,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[a.name,c("span",{className:"text-gray-400 ml-1",children:["(",a.filePath,")"]})]})]},a.sha)),e.currentlyExecuting.entities.length>3&&c("div",{className:"text-xs italic",style:{color:"#005C75"},children:["+",e.currentlyExecuting.entities.length-3," more entities"]})]}),n("p",{className:"text-xs mt-2",style:{color:"#005C75"},children:"This may take 2-3 minutes for environment setup"})]}),e.jobs.length>0&&c("div",{className:"space-y-2",children:[e.jobs.slice(0,5).map((a,s)=>{a.entities?.length||a.entityShas?.length,a.filePaths?.length,a.entityNames?.[0];const o=a.entities&&a.entities.length>0;return n("div",{className:"flex items-start gap-3",children:c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[c("span",{className:"text-sm font-semibold text-gray-700",children:["Job ",s+1]}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:Dc(a.queuedAt)})]}),o&&c("div",{className:"space-y-1 mt-2 max-h-[120px] overflow-y-auto bg-white rounded-md p-2 border border-gray-200",children:[a.entities.slice(0,5).map(i=>c(Z,{to:`/entity/${i.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate",title:`${i.name} - ${i.filePath}`,style:{color:"#005C75"},onMouseEnter:l=>l.currentTarget.style.color="#003d52",onMouseLeave:l=>l.currentTarget.style.color="#005C75",children:[n($e,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[i.name,c("span",{className:"text-gray-400 ml-1",children:["(",i.filePath,")"]})]})]},i.sha)),a.entities.length>5&&c("div",{className:"text-xs text-gray-500 italic",children:["+",a.entities.length-5," more entities"]})]}),a.type==="recapture"&&a.scenarioId&&c("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:["Scenario: ",a.scenarioId]})]})},a.id)}),e.jobs.length>5&&c("div",{className:"text-xs text-gray-500 text-center py-2",children:["+",e.jobs.length-5," more jobs in queue"]})]})]})}function be({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=k("loading"),[l,d]=k(!1),m=pe(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return G(()=>{i("loading"),d(!1);const f=m.current;f?.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:m,src:u,alt:r,onLoad:h,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Ln(e,t,r,a,s){const o=t?.scenarios?.find(Y=>Y.name===e.name),i=!!o?.startedAt,l=!!o?.screenshotStartedAt,d=!!o?.screenshotFinishedAt,m=!!o?.finishedAt,u=1800*1e3,h=l&&!d&&o?.screenshotStartedAt&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!e.metadata?.screenshotPaths?.[0]||!!e.metadata?.executionResult,f=l&&!d,g=o?.error,y=e.metadata?.executionResult?.error,b=[];if(t?.errors&&t.errors.length>0)for(const Y of t.errors)b.push({source:`${Y.phase} phase`,message:Y.message});if(t?.steps)for(const Y of t.steps)Y.error&&b.push({source:Y.name,message:Y.error});const w=!p&&!g&&!y&&b.length>0,x=!!(g||y||h||w),C=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||y?.message||(w?`Analysis error: ${b[0].message}`:null),v=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":o?.errorStack||y?.stack||null,N=(a&&s?s.jobs.some(Y=>Y.entityShas?.includes(a)||Y.type==="analysis"&&Y.entityShas&&Y.entityShas.length===0)||s.currentlyExecuting?.entityShas?.includes(a):!1)&&!i&&!x||!!o?.analyzing&&!i&&!x,E=i&&!l&&!m&&!x,A=(N||E||f)&&!x,I=(N||E)&&r===!1&&!p;let T;I?T="crashed":x?T="error":p||m?T="completed":f?T="capturing":E?T="starting":N?T="queued":T="pending";let M="📷",P="pending",L=!1,_=`Not captured: ${e.name}`;const R="border-gray-300",O=x||I?"bg-red-50":"bg-white";return x||I?(M="⚠️",P="error",_=`Error: ${I?"Analysis process crashed":C||"Unknown error"}`):N?(M="⋯",P="queued",_=`Queued: ${e.name}`):E?(M="⋯",P="starting",L=!0,_=`Starting server for ${e.name}...`):f&&!x?(M="⋯",P="capturing",L=!0,_=`Capturing ${e.name}...`):p&&(M="✓",P="completed",_=e.name),{hasError:x||I,errorMessage:I?"Analysis process crashed":C,errorStack:I?"Process terminated unexpectedly before completing analysis":v,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:A,isQueued:N,isServerStarting:E,status:T,icon:M,iconType:P,shouldSpin:L,title:_,borderColor:R,bgColor:O}}function On({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){const o=Ln(e,void 0,void 0,t,void 0),i=e.metadata?.executionResult,l=!!i,m=(e.metadata?.data?.argumentsData||[]).length,u=i?.returnValue!==void 0&&i?.returnValue!==null,h=i?.sideEffects?.consoleOutput?.length||0,p=i?.timing?.duration||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},b=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?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"},w=a?`border-2 ${b.border}`:"",x=Array.from({length:3},(v,S)=>n("div",{className:`w-1 h-1 rounded-full ${S<f?b.icon.replace("text-","bg-"):"bg-gray-300"}`},S)),C=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
138
|
+
${m} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
|
|
139
|
+
${p}ms`:`Not executed: ${e.name}`;return c(Z,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${w} rounded ${b.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:C,children:[n("div",{className:`${b.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:x}),l&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!o.hasError&&h>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Fn({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){if(t.entityType==="library")return n(On,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Ln(e,r,s,t.sha,a),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${l}`,f=()=>{const y=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${y}/${d}`:y};if(u.isCaptured){const y=e.metadata?.screenshotPaths?.[0];return n(Z,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(be,{screenshotPath:y,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const y={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},x=c(re,{children:[n("style",{children:`
|
|
140
|
+
@keyframes strongPulse {
|
|
141
|
+
0%, 100% { opacity: 0.2; }
|
|
142
|
+
50% { opacity: 1; }
|
|
143
|
+
}
|
|
144
|
+
`}),c("div",{className:`${o==="small"?"text-base":o==="large"?"text-2xl":"text-xl"} font-bold tracking-widest flex items-center justify-center text-gray-600`,children:[n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"},children:"."})]})]});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return x;switch(u.iconType){case"starting":case"capturing":return x;case"error":return n(vn,{...y});case"completed":return n(wn,{...y});default:return x}};return n(Z,{to:f(),className:`${p} ${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:h.iconSize,children:g()})})}async function Oc({request:e,context:t,params:r}){let a=t.analysisQueue;a||(a=await De());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return D({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedRuns:[],totalCompletedRuns:0},{status:500});const d=a.getState(),m=await Pe();let u=null;if(m&&d?.currentlyExecuting?.commitSha){const{project:P,branch:L}=await Ee(m),_=await Ot({projectId:P.id,branchId:L.id,shas:[d.currentlyExecuting.commitSha]});u=_&&_.length>0?_[0]:null}else u=await Ke();const h=async P=>{const L=await Re(P);if(!L)return null;const{getAnalysesForEntity:_}=await Promise.resolve().then(()=>Ro),R=await _(P,!1);return{...L,analyses:R||[]}},p=await Promise.all((d?.jobs||[]).map(async P=>{const L=[];if(P.entityShas&&P.entityShas.length>0){const _=P.entityShas.map(O=>h(O)),R=await Promise.all(_);L.push(...R.filter(O=>O!==null))}return{...P,entities:L}}));let f=null;if(d?.currentlyExecuting){const P=d.currentlyExecuting,L=[];if(P.entityShas&&P.entityShas.length>0){const _=P.entityShas.map(O=>h(O)),R=await Promise.all(_);L.push(...R.filter(O=>O!==null))}f={...P,entities:L}}const g=u?.metadata?.currentRun?.currentEntityShas||[],b=(await Promise.all(g.map(P=>h(P)))).filter(P=>P!==null),w=[];if(m)try{const{project:P,branch:L}=await Ee(m),_=await Ot({projectId:P.id,branchId:L.id,limit:100});for(const R of _){const O=R.metadata?.historicalRuns||[];w.push(...O)}}catch(P){console.error("[activity.tsx] Failed to load historical runs from commits:",P)}const x=[...w].sort((P,L)=>{const _=P.archivedAt||P.createdAt||"";return(L.archivedAt||L.createdAt||"").localeCompare(_)}),C=(o-1)*i,v=C+i,S=x.slice(C,v),N=Math.ceil(x.length/i),E=await Promise.all(S.map(async P=>{const L=P.currentEntityShas||[];if(L.length===0)return{...P,entities:[]};const _=await Promise.all(L.map(R=>h(R)));return{...P,entities:_.filter(R=>R!==null)}})),A=!!f,I=p.length,T=x.filter(P=>{const L=!!P.failedAt,_=P.readyToBeCaptured,R=P.capturesCompleted??0,O=_===void 0?!0:_===0||R>=_;return!L&&!!P.analysisCompletedAt&&O}),M=await Promise.all(T.slice(0,3).map(async P=>{const L=P.currentEntityShas||[];if(L.length===0)return{...P,entities:[]};const _=await Promise.all(L.map(R=>h(R)));return{...P,entities:_.filter(R=>R!==null)}}));return D({state:{...d,jobs:p,currentlyExecuting:f},currentRun:u?.metadata?.currentRun,historicalRuns:E,totalHistoricalRuns:x.length,currentPage:o,totalPages:N,projectSlug:m,commitSha:u?.sha,queueJobs:p,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:A,queuedCount:I,recentCompletedRuns:M,totalCompletedRuns:T.length})}function Fc({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count: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(Z,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
145
|
+
relative pb-4 px-2 text-sm font-medium transition-colors
|
|
146
|
+
${i?"border-b-2":"text-gray-500 hover:text-gray-700"}
|
|
147
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`
|
|
148
|
+
inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full
|
|
149
|
+
${i?"":"bg-gray-200 text-gray-700"}
|
|
150
|
+
`,style:i?{backgroundColor:"#e8f1f5",color:"#005C75"}:{},children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
151
|
+
inline-block w-2 h-2 rounded-full
|
|
152
|
+
${i?"":"bg-gray-400"}
|
|
153
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Yc(e){const t=new Date(e),a=Math.floor((new Date().getTime()-t.getTime())/1e3);if(a<60)return"just now";const s=Math.floor(a/60);if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function zc({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedRuns:i,totalCompletedRuns:l}){const[d,m]=k({}),[u,h]=k({isKilling:!1,current:0,total:0}),p=nt(),f=!!e,g=e?.entities||[],y=!!t?.analysisCompletedAt,b=f,{lastLine:w}=Ye(a,b);return G(()=>{if(!t)return;const x=[t.analyzerPid,t.capturePid].filter(S=>!!S);if(x.length===0)return;const C=async()=>{try{const N=await(await fetch(`/api/process-status?pids=${x.join(",")}`)).json();if(N.processes){const E={};N.processes.forEach(A=>{E[A.pid]={isRunning:A.isRunning,processName:A.processName}}),m(E)}}catch(S){console.error("Failed to fetch process statuses:",S)}};C();const v=setInterval(()=>void C(),5e3);return()=>clearInterval(v)},[t?.analyzerPid,t?.capturePid]),b?c("div",{className:"bg-white rounded-xl shadow-lg p-6",style:{borderWidth:"2px",borderColor:"#005C75"},children:[c("div",{className:"flex items-start justify-between mb-4",children:[c("div",{className:"flex items-center gap-3 mb-2",children:[n("div",{className:"p-2 bg-gray-100 rounded-full animate-spin",children:n(ka,{size:24,className:"text-gray-700"})}),n("h3",{className:"text-xl font-bold text-gray-900",children:y?"Capture in Progress":"Analysis in Progress"})]}),n("button",{onClick:o,className:"px-4 py-2 text-white rounded-md text-sm font-semibold transition-colors",style:{backgroundColor:"#005C75"},onMouseEnter:x=>x.currentTarget.style.backgroundColor="#003d52",onMouseLeave:x=>x.currentTarget.style.backgroundColor="#005C75",children:"View Logs"})]}),y&&(t?.readyToBeCaptured??0)>0&&c("div",{className:"rounded-md p-4 mb-4",style:{backgroundColor:"#f0f5f8",borderColor:"#b3d9e8",borderWidth:"1px"},children:[n("p",{className:"text-sm font-semibold mb-1",style:{color:"#00263d"},children:"Capture Progress:"}),c("div",{className:"flex items-center gap-4",children:[c("p",{className:"text-sm",style:{color:"#004560"},children:[t?.capturesCompleted??0," of"," ",t?.readyToBeCaptured??0," entities captured"]}),n("div",{className:"flex-1 rounded-full h-2",style:{backgroundColor:"#b3d9e8"},children:n("div",{className:"h-2 rounded-full transition-all duration-300",style:{backgroundColor:"#005C75",width:`${(t?.capturesCompleted??0)/(t?.readyToBeCaptured??1)*100}%`}})})]})]}),g&&g.length>0&&c("div",{className:"mb-4",children:[c("p",{className:"text-sm font-semibold text-gray-700 mb-2",children:[y?"Capturing":"Analyzing"," ",g.length," ",g.length===1?"Entity":"Entities",":"]}),n("div",{className:"space-y-3",children:g.map(x=>{const C=x.analyses?.[0],v=C?.scenarios||[],S=C?.status;return c("div",{className:"bg-gray-50 rounded-md p-3",children:[c(Z,{to:`/entity/${x.sha}`,className:"flex items-center gap-1.5 text-sm hover:underline font-medium truncate mb-2",title:`${x.name} - ${x.filePath}`,style:{color:"#005C75"},onMouseEnter:N=>N.currentTarget.style.color="#003d52",onMouseLeave:N=>N.currentTarget.style.color="#005C75",children:[n($e,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[x.name,c("span",{className:"text-gray-500 ml-2 text-xs",children:["(",x.filePath,")"]})]})]}),v.length>0&&n("div",{className:"flex gap-2 flex-wrap",children:v.slice(0,5).map((N,E)=>N.id?n(Fn,{scenario:N,entity:{sha:x.sha,entityType:x.entityType},analysisStatus:S,queueState:r,processIsRunning:b,size:"small"},E):null)})]},x.sha)})})]}),w&&c("div",{className:"flex flex-col gap-2 mb-4",children:[n("p",{className:"text-sm font-semibold text-gray-700",children:"Current Step:"}),n("p",{className:"text-sm text-gray-600 font-mono",children:w})]}),(t?.analyzerPid||t?.capturePid)&&c("div",{className:"flex flex-col gap-4",children:[n("p",{className:"text-sm font-semibold text-gray-700",children:"Running Processes:"}),c("div",{className:"flex items-center justify-between bg-gray-50 rounded-md p-3",children:[c("div",{className:"flex items-center gap-4 flex-wrap",children:[t.analyzerPid&&c("div",{className:"flex items-center gap-2",children:[c("span",{className:"text-xs font-mono bg-gray-200 px-2 py-1 rounded",children:["Analyzer: ",t.analyzerPid]}),d[t.analyzerPid]&&n("span",{className:`text-xs px-2 py-1 rounded ${d[t.analyzerPid].isRunning?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:d[t.analyzerPid].isRunning?"Running":"Stopped"})]}),t.capturePid&&c(re,{children:[t.analyzerPid&&n("span",{className:"text-gray-400",children:"|"}),c("div",{className:"flex items-center gap-2",children:[c("span",{className:"text-xs font-mono bg-gray-200 px-2 py-1 rounded",children:["Capture: ",t.capturePid]}),d[t.capturePid]&&n("span",{className:`text-xs px-2 py-1 rounded ${d[t.capturePid].isRunning?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:d[t.capturePid].isRunning?"Running":"Stopped"})]})]})]}),(d[t.analyzerPid]?.isRunning||d[t.capturePid]?.isRunning)&&c("div",{className:"flex items-center gap-3",children:[u.isKilling&&c("span",{className:"text-xs text-gray-600 font-medium",children:["Killing process ",u.current," of"," ",u.total,"..."]}),n("button",{onClick:()=>{const x=[t.analyzerPid,t.capturePid].filter(S=>!!S&&d[S]?.isRunning);if(x.length===0)return;const C=x.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${C})?`))return;h({isKilling:!0,current:1,total:x.length}),(async()=>{for(let S=0;S<x.length;S++){const N=x[S];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:N,commitSha:s||""})})}catch(E){console.error(`Failed to kill process ${N}:`,E)}S<x.length-1&&h({isKilling:!0,current:S+2,total:x.length})}h({isKilling:!1,current:0,total:0}),p.revalidate()})()},disabled:u.isKilling,className:"px-3 py-1 bg-red-600 text-white rounded-md text-xs font-semibold hover:bg-red-700 transition-colors whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed",children:u.isKilling?"Killing...":"Kill All Processes"})]})]})]})]}):c("div",{className:"space-y-6",children:[c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-2 bg-gray-200 rounded-lg",children:n(Nr,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Current Activity"}),c("p",{className:"text-gray-500",children:["There are no analyses currently running. Trigger an analysis from the"," ",n(Z,{to:"/git",className:"text-[#005C75] underline hover:text-[#004a5e]",children:"Git"})," ","or"," ",n(Z,{to:"/files",className:"text-[#005C75] underline hover:text-[#004a5e]",children:"Files"})," ","page."]})]}),i&&i.length>0&&c("div",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Recent Completed Analyses"}),n("div",{className:"space-y-3",children:i.map(x=>{const C=x.analysisCompletedAt||x.archivedAt||x.createdAt,v=x.entities&&x.entities.length>0;return c("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n(wn,{size:18,className:"text-green-600"}),n("span",{className:"text-sm font-semibold text-gray-900",children:"Completed"}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:C?Yc(C):"Unknown"})]}),v&&c("div",{className:"ml-7 space-y-1",children:[x.entities.slice(0,3).map(S=>c(Z,{to:`/entity/${S.sha}`,className:"flex items-center gap-1.5 text-sm hover:underline truncate",title:`${S.name} - ${S.filePath}`,style:{color:"#005C75"},onMouseEnter:N=>N.currentTarget.style.color="#003d52",onMouseLeave:N=>N.currentTarget.style.color="#005C75",children:[n($e,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[S.name,c("span",{className:"text-gray-400 ml-1 text-xs",children:["(",S.filePath,")"]})]})]},S.sha)),x.entities.length>3&&c("div",{className:"text-xs text-gray-500 italic",children:["+",x.entities.length-3," more entities"]})]})]},x.id)})}),l>3&&n("div",{className:"mt-4 text-center",children:n(Z,{to:"/activity/historic",className:"text-sm font-medium",style:{color:"#005C75"},onMouseEnter:x=>x.currentTarget.style.color="#003d52",onMouseLeave:x=>x.currentTarget.style.color="#005C75",children:"View All Historic Activity →"})})]})]})}function Bc({queueJobs:e,state:t,currentRun:r}){return!e||e.length===0?c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-3 bg-gray-200 rounded-lg",children:n(Ia,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Queued Jobs"}),n("p",{className:"text-gray-500",children:"Analysis jobs will appear here when they are queued but not yet started."})]}):n("div",{children:n(Lc,{state:t,currentRun:r})})}function Uc({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s}){return t===0?c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-3 bg-gray-200 rounded-lg",children:n(Sr,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Historic Activity"}),n("p",{className:"text-gray-500",children:"Completed analyses will appear here for historical reference."})]}):c("div",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"space-y-3",children:e.map(o=>{const i=!!o.failedAt,l=o.readyToBeCaptured,d=o.capturesCompleted??0,m=l===void 0?!0:l===0||d>=l,u=!i&&!!o.analysisCompletedAt&&m,h=o.createdAt?new Date(o.createdAt):null,p=o.failedAt?new Date(o.failedAt):o.analysisCompletedAt?new Date(o.analysisCompletedAt):null,f=h&&p?(p.getTime()-h.getTime())/1e3:null,g=o.entities&&o.entities.length>0;return n("div",{className:`border rounded-lg p-4 ${i?"bg-red-50 border-red-200":u?"bg-green-50 border-green-200":"bg-gray-50 border-gray-200"}`,children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[i?n(vn,{size:20,className:"text-red-500"}):u?n(wn,{size:20,className:"text-green-500"}):n(Nr,{size:20,className:"text-gray-400"}),n("span",{className:"text-sm font-semibold text-gray-900",children:i?"Failed":u?"Completed":"Incomplete"}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:o.archivedAt?new Date(o.archivedAt).toLocaleString():o.createdAt?new Date(o.createdAt).toLocaleString():"Unknown"})]}),g&&c("div",{className:"ml-7 mt-2 space-y-2 max-h-[300px] overflow-y-auto bg-white rounded-md p-2 border border-gray-200",children:[o.entities.slice(0,5).map(y=>{const b=y.analyses?.[0],w=b?.scenarios||[];return c("div",{className:"pb-2 border-b last:border-b-0 border-gray-100",children:[c(Z,{to:`/entity/${y.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate mb-1",title:`${y.name} - ${y.filePath}`,style:{color:"#005C75"},onMouseEnter:x=>x.currentTarget.style.color="#003d52",onMouseLeave:x=>x.currentTarget.style.color="#005C75",children:[n($e,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[y.name,c("span",{className:"text-gray-400 ml-1",children:["(",y.filePath,")"]})]})]}),w.length>0&&n("div",{className:"flex gap-1.5 flex-wrap mt-1.5",children:w.slice(0,5).map((x,C)=>x.id?n(Fn,{scenario:x,entity:{sha:y.sha,entityType:y.entityType},analysisStatus:b?.status,queueState:void 0,processIsRunning:!1,size:"small"},C):null)})]},y.sha)}),o.entities.length>5&&c("div",{className:"text-xs text-gray-500 italic pt-1",children:["+",o.entities.length-5," more entities"]})]}),o.failureReason&&n("p",{className:"text-xs text-red-600 mt-2 font-mono ml-7",children:o.failureReason})]}),f!==null&&c("div",{className:"text-xs text-gray-500",children:[f.toFixed(1),"s"]})]})},o.id)})}),a>1&&c("div",{className:"mt-6 flex items-center justify-between border-t border-gray-200 pt-4",children:[c("div",{className:"text-sm text-gray-600",children:["Showing ",(r-1)*20+1," -"," ",Math.min(r*20,t)," of"," ",t," runs"]}),c("div",{className:"flex gap-2",children:[r>1&&n(Z,{to:`/activity/${s}?page=${r-1}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors",children:"Previous"}),r<a&&n(Z,{to:`/activity/${s}?page=${r+1}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors",children:"Next"})]})]})]})}const qc=_e(function(){const t=Ie(),r=wr(),[a,s]=k(!1),o=r.tab||"current";return c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-gray-600",children:"View queued, current, and historical analysis activity"})]}),n(Fc,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(zc,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedRuns:t.recentCompletedRuns,totalCompletedRuns:t.totalCompletedRuns}),o==="queued"&&n(Bc,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(Uc,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o}),a&&t.projectSlug&&n(rt,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]})}),Wc=Object.freeze(Object.defineProperty({__proto__:null,default:qc,loader:Oc},Symbol.toStringTag,{value:"Module"}));async function da(e,t,r){await we();const a=await ze({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=ie();if(!s)throw new Error("Project root not found");const o=ae.join(s,".codeyam","config.json"),i=JSON.parse(se.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=`/tmp/codeyam/local-dev/${l}/codeyam/log.txt`;try{se.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Ee(l),u=m.metadata?.packageManager||"npm",h=m.metadata?.webapps?.[0]?.framework??xt.Next,p=3112,f=`/tmp/codeyam/local-dev/${l}/project`,g=m.metadata?.webapps||[];if(g.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=g.length>1?g.find(S=>a.filePath.includes(S.path??""))??g[0]:g[0];await bt(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const N of S.scenarios)(!t||N.name===t)&&(delete N.screenshotStartedAt,delete N.screenshotFinishedAt,delete N.interactiveStartedAt,delete N.interactiveFinishedAt,delete N.error,delete N.errorStack)});const{jobId:b}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),x=(()=>{const S=y?.startCommand;if(!S)return`${u} ${u==="npm"?"run ":""}dev`;const N=S.args?.map(T=>T.replace(/\$PORT/g,String(p)))??[],E=[],A=i.environmentVariables||[];for(const T of A)if(T.key&&T.value!==void 0){const M=String(T.value).replace(/'/g,"'\\''");E.push(`${T.key}='${M}'`)}if(S.env)for(const[T,M]of Object.entries(S.env)){const L=String(M).replace(/\$PORT/g,String(p)).replace(/'/g,"'\\''");E.push(`${T}='${L}'`)}const I=E.length>0?E.join(" ")+" ":"";return S.command==="sh"&&N[0]==="-c"&&N[1]?`${I}sh -c "${N[1]}"`:`${I}${S.command} ${N.join(" ")}`})(),C={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:f}]},{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 ${f}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:b,analysisId:e,scenarioId:t,projectPath:f,projectSlug:l,port:p,packageManager:u,framework:h,instructions:C}}async function Gc({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 D({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 De()),!o)return D({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await da(a,s,o);return D({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),D({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Hc({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await De()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return D({error:"Missing required field: analysisId"},{status:400});const i=await da(s,o,r);return D({...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),D({error:"Failed to setup debug environment",details:s},{status:500})}}const Kc=Object.freeze(Object.defineProperty({__proto__:null,action:Hc,loader:Gc},Symbol.toStringTag,{value:"Module"}));async function Vc({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await De()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return D({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return D({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const l=await Tl(s,i,r);return console.log("[API] Recapture queued",l),D({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),D({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Jc=Object.freeze(Object.defineProperty({__proto__:null,action:Vc},Symbol.toStringTag,{value:"Module"}));function Yn(e,t){const r=e.metadata?.isUncommitted===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(i=>i.scenarios&&i.scenarios.length>0);if(!r){const i=!!e.metadata?.previousVersionWithAnalyses,l=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return i||l?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=!!e.metadata?.previousCommittedSha;if(!!e.metadata?.previousVersionWithAnalyses||s){const i=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===e.metadata?.previousVersionWithAnalyses;return a&&!i?{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 zn(e){return Yn(e).hasOutdatedSimulations}const Pt=70;function Qc({scenarios:e,analysis:t,selectedScenario:r,entitySha:a,cacheBuster:s,activeTab:o,entityType:i,entity:l,queueState:d,processIsRunning:m,viewMode:u,setViewMode:h,onDebugSetup:p,debugFetcher:f}){const g=pe(null),[y,b]=k(new Set);G(()=>{g.current&&o==="scenarios"&&g.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[r?.id,o]);const w=v=>`/entity/${a}/scenarios/${v}`,x=v=>{b(S=>{const N=new Set(S);return N.has(v)?N.delete(v):N.add(v),N})},C=(v,S=2)=>{const E=v.split(`
|
|
154
|
+
`).slice(0,S).join(" ").trim();return E.length>Pt?E.substring(0,Pt-3):(v.split(`
|
|
155
|
+
`).length>S||v.length>E.length,E)};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3",children:[h&&c("div",{children:[n("div",{className:"text-[10px] text-[#626262] font-medium mb-[6px]",children:"View"}),c("div",{className:"grid grid-cols-2 gap-0",role:"group","aria-label":"View mode selector",children:[n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-l-[4px] border border-[#c7c7c7] transition-colors ${u==="screenshot"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("screenshot"),"aria-label":"Screenshot view","aria-pressed":u==="screenshot",children:"📸 Screenshot"}),n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-r-[4px] border border-[#c7c7c7] border-l-0 transition-colors ${u==="interactive"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("interactive"),"aria-label":"Interactive view","aria-pressed":u==="interactive",children:"🎮 Interactive"})]})]}),r&&c("div",{className:"grid grid-cols-2 gap-1",children:[n(Z,{to:`/entity/${a}/edit/${r.id}`,className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] no-underline flex items-center justify-center",title:"Edit Scenario Data",children:"Edit Scenario"}),n("button",{className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:bg-gray-400 disabled:text-gray-600 disabled:cursor-not-allowed flex items-center justify-center",onClick:p,disabled:f?.state!=="idle",title:"Setup Debug Environment",children:f?.state==="idle"?"Debug Scenario":"Setting up..."})]}),l&&l.filePath&&n("div",{children:n(Z,{to:`/entity/${a}/create-scenario`,className:"w-full px-[10px] 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] no-underline flex items-center justify-center",children:"Create New Scenario"})}),n("div",{className:"border-t border-[#e1e1e1] pt-3",children:n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Scenarios"})}),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((v,S)=>{const N=r?.id===v.id,E=y.has(v.id||"");return v.id?c(Z,{to:w(v.id),ref:N?g:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${N?"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(Fn,{scenario:v,entity:{sha:a,entityType:i},analysisStatus:t?.status,queueState:d,processIsRunning:m,size:"large",cacheBuster:s,viewMode:u})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${E?"":"line-clamp-1"}`,children:v.name}),v.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[E?v.description:C(v.description),!E&&v.description.length>Pt&&c(re,{children:["...",n("button",{onClick:A=>{A.preventDefault(),A.stopPropagation(),x(v.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),E&&v.description.length>Pt&&n("button",{onClick:A=>{A.preventDefault(),A.stopPropagation(),x(v.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},S):null})})})]})}function Zc({scenario:e,analysis:t,entity:r}){const a=e.metadata?.executionResult||null,s=e.metadata?.data?.argumentsData||[],o=i=>{if(!i)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const l=[],d=i.sideEffects?.consoleOutput||[];d.length>0&&(l.push(`Console Output: ${d.length} log ${d.length===1?"entry":"entries"} captured`),d.forEach(h=>{l.push(` [${h.level.toUpperCase()}] ${h.args.join(" ")}`)}));const m=i.sideEffects?.fileWrites||[];m.length>0&&(l.push(`
|
|
156
|
+
File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(h=>{l.push(` ${h.operation}: ${h.path}${h.size?` (${h.size} bytes)`:""}`)}));const u=i.sideEffects?.apiCalls||[];return u.length>0&&(l.push(`
|
|
157
|
+
API Calls: ${u.length} ${u.length===1?"call":"calls"} made`),u.forEach(h=>{l.push(` ${h.method} ${h.url}${h.status?` → ${h.status}`:""}${h.duration?` (${h.duration}ms)`:""}`)})),i.error&&l.push(`
|
|
158
|
+
Error: ${i.error.name||"Error"}: ${i.error.message}`),l.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":l.join(`
|
|
159
|
+
`)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children: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"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const Mt=10,Xc=1024;function ed({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a}){const[s,o]=k(null),i=pe(null),l=ee(()=>[...a].sort((y,b)=>y.width-b.width),[a]),{fittingPresets:d,overflowPresets:m}=ee(()=>{const y=[],b=[];for(const w of l)w.width<=Xc?y.push(w):b.push(w);return b.sort((w,x)=>x.width-w.width),{fittingPresets:y,overflowPresets:b}},[l]),u=V(y=>{if(!i.current)return null;const b=i.current.getBoundingClientRect(),w=y-b.left,x=b.width,C=x/2,S=(d.length>0?d[d.length-1].width:0)/2,N=C-S,E=C+S,A=m.length>0?(m.length-1)*Mt:0;if(m.length>0){if(w<N){if(w<=A){const T=Math.min(Math.floor(w/Mt),m.length-1);return m[T]}return m[m.length-1]}if(w>E){const T=x-w;if(T<=A){const M=Math.min(Math.floor(T/Mt),m.length-1);return m[M]}return m[m.length-1]}}const I=Math.abs(w-C);for(let T=d.length-1;T>=0;T--){const M=d[T],P=d[T-1],L=M.width/2,_=P?P.width/2:0;if(I<=L&&I>=_)return M}return d[0]||m[m.length-1]||null},[d,m]),h=V(y=>{const b=u(y.clientX);o(b)},[u]),p=V(()=>{o(null)},[]),f=V(y=>{const b=u(y.clientX);b&&r(b)},[u,r]),g=s||{name:t,width:e};return c("div",{ref:i,className:"relative h-6 bg-[#f6f9fc] shrink-0 overflow-hidden cursor-pointer",onMouseMove:h,onMouseLeave:p,onClick:f,children:[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-[rgba(0,92,117,0.15)]",style:{width:`${e}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:d.map(y=>{const b=y.width===e,w=s?.name===y.name,x=y.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${x}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${b||w?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${x}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${b||w?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((y,b)=>{const w=b*Mt,x=y.width===e,C=s?.name===y.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${x||C?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${x||C?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${s?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[g.name," - ",g.width,"px"]})})]})}function td({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=k(""),[i,l]=k(""),d=()=>{const u=s.trim();if(!u){l("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:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),l("")},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})]}),c("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",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 disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function nd(e){const[t,r]=k([]),a=e?`codeyam-custom-sizes-${e}`:null;G(()=>{if(!a||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(a);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[a]);const s=V(l=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=V((l,d,m)=>{r(u=>{const h=u.findIndex(g=>g.name===l),p={name:l,width:d,height:m};let f;return h>=0?(f=[...u],f[h]=p):f=[...u,p],s(f),f})},[s]),i=V(l=>{r(d=>{const m=d.filter(u=>u.name!==l);return s(m),m})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}const dr=1440,Tt=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function ua({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0}){const m=fe(),[u,h]=k(!1),[p,f]=k(!1),[g,y]=k({name:"Desktop",width:dr,height:900}),[b,w]=k(dr),[x,C]=k(1),{customSizes:v,addCustomSize:S,removeCustomSize:N}=nd(l),E=ee(()=>[...Tt,...v],[v]),A=(W,ne)=>{w(W);const Me=E.find(ye=>ye.width===W&&ye.height===ne);y({name:Me?.name||"Custom",width:W,height:ne})},I=W=>{w(W.width),y({name:W.name,width:W.width,height:W.height})},T=W=>{S(W,g.width,g.height??900),f(!1),y(ne=>({...ne,name:W}))},M=(W,ne)=>{w(W);const Me=E.find(ye=>ye.width===W&&ye.height===ne);y(ye=>({name:Me?.name||"Custom",width:W,height:ye.height}))},P=e?.metadata?.screenshotPaths?.[0],L=ee(()=>!e||!t?.status?.scenarios?null:t.status.scenarios.find(W=>W.name===e.name),[e,t?.status?.scenarios]),_=ee(()=>{const W=[];if(t?.status?.errors&&t.status.errors.length>0)for(const ne of t.status.errors)W.push({source:`${ne.phase} phase`,message:ne.message,stack:ne.stack});if(t?.status?.steps)for(const ne of t.status.steps)ne.error&&W.push({source:ne.name,message:ne.error,stack:ne.errorStack});return W},[t?.status?.errors,t?.status?.steps]),R=L?.error||(e?.metadata?.error?"Error during capture":null),O=L?.errorStack,{interactiveServerUrl:Y,isStarting:J,isLoading:F,showIframe:q,iframeKey:K,onIframeLoad:$}=Rn({analysisId:t?.id,scenarioId:e?.id,scenarioName:e?.name,projectSlug:l,enabled:a==="interactive"}),U=ee(()=>Y||null,[Y]),j=!i&&o&&e&&!e.metadata?.screenshotPaths?.[0]&&t?.status?.scenarios?.some(W=>W.name===e.name&&W.screenshotStartedAt&&!W.screenshotFinishedAt),{lastLine:B}=Ye(l,i||a==="interactive"||j||!1);return e?c(re,{children:[n("main",{className:"flex-1 bg-[#f9f9f9] overflow-auto flex flex-col min-w-0",children:(i||j)&&!P&&!R&&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:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:j?`Capturing ${r?.name}`:`Analyzing ${r?.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:j?`Taking screenshots for ${t?.scenarios?.length||0} scenario${t?.scenarios?.length!==1?"s":""}...`:`Generating simulations and scenarios for this ${r?.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),B&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:B,children:B})]})]})}),l&&n("button",{onClick:()=>h(!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"&&(P||R)||a==="interactive"&&(U||J)||a==="data"?c(re,{children:[R&&!P&&n("div",{className:"bg-red-50 border-l-4 border-red-500 mx-5 mt-4 p-4 rounded-r max-h-[400px] overflow-auto",role:"alert",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-red-500 text-xl shrink-0","aria-hidden":"true",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-sm font-semibold text-red-800 m-0 mb-2",children:"Capture Error"}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-700 m-0 mb-2 font-mono whitespace-pre-wrap wrap-break-word",children:R})}),O&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-600 cursor-pointer hover:text-red-800 font-medium",children:"View stack trace"}),n("div",{className:"mt-2 p-3 bg-red-100 rounded max-h-[300px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:O})})]})]})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[U&&n("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center",children:n(Ko,{presets:[...Tt],customSizes:v,currentWidth:g.width,currentHeight:g.height??900,scale:x,onSizeChange:A,onSaveCustomSize:()=>f(!0),onRemoveCustomSize:N})}),U&&n("div",{className:"bg-[#f6f9fc] border-b border-[rgba(0,92,117,0.25)] flex justify-center",children:n("div",{style:{maxWidth:`${Tt[Tt.length-1].width}px`,width:"100%"},children:n(ed,{currentViewportWidth:b,currentPresetName:g.name,onDevicePresetClick:I,devicePresets:E})})}),n($n,{scenarioId:e.id,scenarioName:e.name,iframeUrl:U,isStarting:J,isLoading:F,showIframe:q,iframeKey:K,onIframeLoad:$,onScaleChange:C,onDimensionChange:M,projectSlug:l,defaultWidth:g.width,defaultHeight:g.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(Zc,{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:(P||!R)&&n(be,{screenshotPath:P,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&&!P?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),B&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:B})]}),l&&n("button",{onClick:()=>h(!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"})]})]})})}):R?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),c("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),c("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(Z,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),c("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:R})})]}),O&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 max-h-[400px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:O})})]})]})]})})]}):_.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Error"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:_.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${_.length} errors occurred during analysis. Screenshot capture was not completed.`}),_.map((W,ne)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:W.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:W.message})}),W.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:W.stack})})]})]},ne))]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),u&&l&&n(rt,{projectSlug:l,onClose:()=>h(!1)}),p&&n(td,{width:g.width,height:g.height??900,onSave:T,onCancel:()=>f(!1)})]}):!o&&r?i?n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:j?"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."}),B&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:B}),l&&n("button",{onClick:()=>h(!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"})]})}):_.length>0?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 bg-[#f6f9fc] overflow-auto",children:c("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl",children:[c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:_.length===1?"An error occurred during analysis. No scenarios were generated.":`${_.length} errors occurred during analysis. No scenarios were generated.`}),_.map((W,ne)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:W.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:W.message})}),W.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:W.stack})})]})]},ne))]})]}),r.filePath&&n("div",{className:"flex justify-center mt-4",children:n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[42px] px-6 py-2 bg-[#005c75] text-white border-none rounded-lg text-sm font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Retrying...":"Retry Analysis"})})]})}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})}):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"})})}function ur({hasIndirectBadge:e,onAnalyze:t}){return c(re,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),c("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function rd({entity:e,history:t}){const[r,a]=k("entity"),[s,o]=k(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ee(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(p=>{p.scenarios?.forEach(f=>{u.has(f.name)||u.set(f.name,[]),u.get(f.name).push({version:h,analysis:p,scenario:f})})})}),Array.from(u.entries()).map(([h,p])=>({name:h,description:p[0]?.scenario.description||"",versions:p.sort((f,g)=>{const y=new Date(f.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-y})}))},[t]),d=l.length,m=u=>{o(h=>{const p=new Set(h);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>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})]}),c("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"?c("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[u.sha===e?.sha&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c("span",{className:"text-xs font-mono text-[#646464] leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",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((p,f)=>n("div",{children:!p.scenarios||p.scenarios.length===0?n(ur,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):c(re,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[p.scenarios.length," scenario",p.scenarios.length!==1?"s":""]})]})}),p.metadata?.scenarioChangesOverview&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),p.scenarios&&p.scenarios.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:p.scenarios.map((g,y)=>{const b=g.metadata?.screenshotPaths?.[0],w=`${g.name}-${y}`;return c("div",{className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(be,{screenshotPath:b,alt:g.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:g.name})})]},w)})})})]})},p.id||f))}):n(ur,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,h)=>{const p=s.has(u.name),f=p?u.versions:u.versions.slice(0,1),g=u.versions.length-1;return u.versions[0]?.version.sha,e?.sha,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((b,w)=>{const{version:x,analysis:C,scenario:v}=b,S=v.metadata?.screenshotPaths?.[0],N=w===0;return c("div",{className:`flex gap-5 items-start ${N?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n("div",{className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0",children:S?n(be,{screenshotPath:S,alt:v.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[x.sha===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"}),N&&u.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),c("p",{className:"text-xs font-mono text-[#646464] m-0 leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:x.sha.substring(0,8)})]}),C.createdAt&&c("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"})]})]},`${x.sha}-${w}`)}),g>0&&c("button",{onClick:()=>m(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}const ad="data:image/svg+xml,%3csvg%20width='18'%20height='14'%20viewBox='0%200%2018%2014'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M2.46802%2013.5264C1.10497%2013.5264%20-3.51454e-08%2012.4214%20-7.84995e-08%2011.0583L-3.51715e-07%202.46848C-3.95069e-07%201.10542%201.10497%200.000452947%202.46802%200.000453841L10.3546%200.000453496L15.2058%200.000453284C16.5689%200.000453225%2017.6738%201.10542%2017.6738%202.46847L17.6738%2011.0583C17.6738%2012.4214%2016.5689%2013.5264%2015.2058%2013.5264L2.46802%2013.5264Z'%20fill='%23F0E4FF'/%3e%3cpath%20d='M14.7146%2010.9579V7.27751L11.2361%203.7832L6.97294%208.06716L5.642%206.75757L2.96094%209.41945V10.9579H14.7146Z'%20fill='%239040F5'/%3e%3ccircle%20cx='5.57991'%20cy='4.1639'%20r='1.59554'%20fill='%239040F5'/%3e%3c/svg%3e";function Fe({type:e}){const t={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#0DBFE9",bgColor:"bg-cyan-100",bgHex:"#cffafe"},type:{iconColor:"#dc2626",bgColor:"bg-red-100",bgHex:"#fee2e2"},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"}},r=t[e]||t.other,a=()=>{switch(e){case"library":return n(Ar,{size:16,color:r.iconColor});case"visual":return n("img",{src:ad,alt:"",style:{width:22,height:17}});case"type":return n(ja,{size:16,color:r.iconColor});case"data":return n(Sr,{size:16,color:r.iconColor});case"index":return n($a,{size:16,color:r.iconColor});case"functionCall":return n(Wn,{size:16,color:r.iconColor});case"class":return n(Ra,{size:16,color:r.iconColor});case"method":return n(Wn,{size:16,color:r.iconColor});case"other":return n($e,{size:16,color:r.iconColor});default:return n($e,{size:16,color:r.iconColor})}};return n("span",{className:`flex items-center justify-center w-8 h-8 rounded ${r.bgColor}`,children:a()})}function mr({entity:e,analysisInfo:t,from:r}){return n(Z,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(be,{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(Fe,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Fe,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?c(re,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(re,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]})})]})]})},e.sha)}const hr=e=>{const t=e.analysisStatus?.status||"not_analyzed",r=e.analysisStatus?.scenarioCount||0,a=e.analysisStatus?.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 sd({importedEntities:e,importingEntities:t}){const[r]=bn(),a=r.get("from"),s=e.length>0,o=t.length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),s?n("div",{className:"p-6 space-y-4",children:e.map(i=>n(mr,{entity:i,analysisInfo:hr(i),from:a},i.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),o?n("div",{className:"p-6 space-y-4",children:t.map(i=>n(mr,{entity:i,analysisInfo:hr(i),from:a},i.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 od({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(sd,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function id({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(ft,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function ft({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,l]=k(r||t<2);if(G(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(re,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>n("div",{className:"py-0.5",children:n(ft,{data:m,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=p=>Array.isArray(p)&&p.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[m.length,"}"]})]}),i?c(re,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(p=>{const f=e[p],g=u(f),y=h(f);return n("div",{className:"py-0.5",children:g?n(Bn,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(Un,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(re,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(ft,{data:f,depth:t+1,defaultExpanded:r,maxDepth:a})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Bn({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=k(a||r<2),l=Object.keys(t);return G(()=>{i(a||r<2)},[a,r]),c(re,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(re,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const m=t[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(Bn,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):h?n(Un,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):c(re,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(ft,{data:m,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Un({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=k(a||r<2);return G(()=>{i(a||r<2)},[a,r]),c(re,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(re,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const m=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:m?n(Bn,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(Un,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):n(ft,{data:l,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function un({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors ${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 pr({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 ${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 fr({call:e,scenarioName:t}){const[r,a]=k(!1),[s,o]=k("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const g=[];return p&&g.push(`${p.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},m=ee(()=>{try{const p=JSON.parse(e.response);return p.choices?.[0]?.message?.content?p.choices[0].message.content:p.content?.[0]?.text?p.content[0].text:e.response}catch{return e.response}},[e.response]),u=ee(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=ee(()=>{if(t)return t;try{return JSON.parse(e.props)?.scenario?.name||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${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&&c("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"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),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:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const gr=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function ld({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){const[o,i]=k("entity"),[l,d]=k("isolatedDataStructure"),[m,u]=k(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=k("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ee(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const C=[...s.entityCalls,...s.analysisCalls],v=C.filter(N=>N.object_type==="entity"||gr.includes(N.prompt_type)),S=C.filter(N=>N.object_type!=="entity"&&!gr.includes(N.prompt_type));return v.sort((N,E)=>E.created_at-N.created_at),S.sort((N,E)=>E.created_at-N.created_at),{entityLlmCalls:v,scenarioLlmCalls:S,totalLlmCalls:C.length}},[s]),b=[{id:"isolatedDataStructure",title:"Isolated Data Structure",data:e?.metadata?.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:t?.metadata?.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:e?.metadata?.isolatedDataStructure?.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"keyAttributes",title:"Key Attributes",data:t?.metadata?.keyAttributes,description:"Important attributes identified during analysis"},{id:"importedExports",title:"Imported Dependencies",data:e?.metadata?.importedExports,description:"The imported dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:t?.metadata?.scenariosDataStructure,description:"Structure template used across all scenarios"}],w=b.filter(C=>C.data!==void 0&&C.data!==null).length;let x=null;if(o==="entity"){const C=b.find(v=>v.id===l);C&&C.data!==void 0&&C.data!==null&&(x={title:C.title,description:C.description,data:C.data})}else if(o==="scenarios"&&m){const C=r.find(v=>(v.id||v.name)===m.scenarioId);C&&(x={title:C.name,description:C.description||"Scenario data and configuration",data:C.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(un,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(un,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(un,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),t?.metadata?.analyzerVersion&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(C=>n(fr,{call:C},C.id)):g.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):g.map(C=>n(fr,{call:C},C.id))})]}):c("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?c(re,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),w===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:b.map(C=>{const v=C.data!==void 0&&C.data!==null;return n(pr,{label:C.title,isActive:l===C.id,onClick:()=>d(C.id),disabled:!v},C.id)})})]}):c(re,{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(C=>{const v=C.id||C.name,S=m?.scenarioId===v;return n(pr,{label:C.name,isActive:S,onClick:()=>u({scenarioId:v})},v)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:x?n(cd,{title:x.title,description:x.description,data:x.data}):o==="scenarios"&&r.length===0?n(yr,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(yr,{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 yr({title:e,description:t,onAnalyze:r}){return c("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function cd({title:e,description:t,data:r}){const[a,s]=k(!0),[o,i]=k("Copy JSON");return c(re,{children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>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(id,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function dd({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=fe();return G(()=>{if(e?.sha&&s.state==="idle"&&!s.data){const o=t?.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e?.sha,t?.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(ld,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function xn({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o}){const[i,l]=k(!1),d=V(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),s)}).catch(m=>{console.error("Failed to copy:",m)})},[e,s]);return n("button",{onClick:d,className:a,disabled:i,"aria-label":o||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?r:t})}const ud={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},md={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},hd=2e3,pd=e=>{if(!e)return"typescript";switch(e.split(".").pop()?.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 fd({entity:e,entityCode:t}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e?.filePath})]}),t&&n(xn,{content:t,label:"Copy Code",duration:hd,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(ms,{language:pd(e?.filePath),style:hs,showLineNumbers:!0,customStyle:ud,lineNumberStyle:md,children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const gd=({data:e})=>[{title:e?.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function yd({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 xd({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"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",m=l[1]||null,u=l[2]||null,h=r.analysisQueue,p=h?h.getState():{paused:!1,jobs:[]},[f,g,y,b,w]=await Promise.all([Re(a),Kt(a,!1),Pe(),Ke(),jo(ie()||process.cwd())]),x=g&&g.length>0?g[0]:null;let C={importedEntities:[],importingEntities:[]},v=null,S=[];return f&&(C=await qr(f),v=await Gr(f),S=await Hr(f)),D({entity:f??void 0,analysis:x??void 0,projectSlug:y,from:o,relatedEntities:C,entityCode:v??void 0,history:S,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:b,hasAnApiKey:w,queueState:p})}const bd=_e(function(){const t=Ie(),s=(wr()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,l=s[2]||null,d=t.entity,m=t.analysis,u=t.projectSlug;t.from;const h=t.relatedEntities,p=t.entityCode,f=t.history,g=t.currentCommit,y=t.hasAnApiKey,b=t.queueState,w=m?.scenarios||[],x=tt(),C=pe(null);G(()=>{C.current===null&&(C.current=window.history.length)},[]);const v=()=>{if(typeof window>"u")return;const Q=window.history.state;if(Q===null||Q?.idx===void 0||Q?.idx===0)x("/");else{const me=window.history.length,de=C.current;if(de!==null&&me>de){const xe=me-de+1;x(-xe)}else x(-1)}},S=!!b.currentlyExecuting,N=o,E=ee(()=>{if(N!=="scenarios")return null;if(i){const Q=w.find(me=>me.id===i);if(Q)return Q}return w.length>0?w[0]:null},[N,i,w]),[A,I]=k(()=>l||(d?.entityType==="library"?"data":"screenshot"));G(()=>{l&&l!==A&&I(l)},[l]);const[T,M]=k(!1),[P,L]=k(""),[_,R]=k(!1),[O,Y]=k(Date.now()),[J,F]=k(null),[q,K]=k(!1),[$,U]=k(!1),j=fe(),B=fe(),te=fe(),ue=fe(),W=nt(),ne=g?.metadata?.currentRun,Me=!!ne?.createdAt&&!ne?.analysisCompletedAt,ye=b.jobs.some(Q=>Q.entityShas?.includes(d?.sha||"")||Q.type==="analysis"&&Q.commitSha===g?.sha&&Q.entityShas&&Q.entityShas.length===0),it=ne?.currentEntityShas?.includes(d?.sha||"")??!1,lt=it;d?.metadata?.defaultWidth||m?.metadata?.defaultWidth,j.state==="submitting"||j.state,ee(()=>!!E?.metadata?.interactiveExamplePath,[E]);const{isCompleted:ct}=Ye(u,_);G(()=>{j.state==="idle"&&j.data&&(j.data.success?setTimeout(()=>{Y(Date.now()),W.revalidate(),R(!1)},1500):j.data.error&&(R(!1),alert(`Recapture failed: ${j.data.error}`)))},[j.state,j.data,W]),G(()=>{_&&ct&&setTimeout(()=>{Y(Date.now()),W.revalidate(),R(!1)},1500)},[_,ct,W]),G(()=>{if(B.state==="idle"&&B.data)if(B.data.success){F(B.data),K(!0);const Q=B.data.jobId;if(Q){const me=async()=>{try{const xe=await fetch("/api/queue?queryType=job&jobId="+encodeURIComponent(Q));if(!xe.ok){const Le=await xe.text();console.error("[Debug Setup] Poll failed with status",xe.status,":",Le);return}(await xe.json()).status==="completed"&&(clearInterval(de),F(Le=>Le?{...Le,complete:!0,instructions:{title:"Debug Environment Ready ✓",sections:Le.instructions?.sections?.map(X=>X.heading==="Status"?{heading:"Status",items:[{content:"Setup complete! Your debug environment is ready."},...X.items.slice(1)]}:X.heading==="What's Happening"?null:X.heading==="Next Steps (Once Complete)"?{...X,heading:"Next Steps"}:X).filter(Boolean)||[]}}:null))}catch(xe){console.error("[Debug Setup] Error polling queue:",xe)}},de=setInterval(()=>{me().catch(()=>{})},2e3);return()=>{clearInterval(de)}}else console.warn("[Debug Setup] No job ID returned from debug setup!")}else B.data.error&&(console.error("[Debug Setup] Error:",B.data.error),alert(`Debug setup failed: ${B.data.error}`))},[B.state,B.data]),G(()=>{te.state==="idle"&&te.data&&(te.data.success?setTimeout(()=>{Y(Date.now()),W.revalidate(),R(!1)},1500):te.data.error&&(R(!1),alert(`Recapture failed: ${te.data.error}`)))},[te.state,te.data,W]);const Ve=()=>{d&&ue.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})};G(()=>{ue.state==="idle"&&ue.data&&(ue.data.success?W.revalidate():ue.data.error&&alert(`Analysis failed: ${ue.data.error}`))},[ue.state,ue.data,d?.sha,W]),G(()=>{const Q=setTimeout(()=>{W.revalidate()},500);return()=>clearTimeout(Q)},[]),G(()=>{if(Me||lt){const Q=setInterval(()=>{W.revalidate()},3e3);return()=>clearInterval(Q)}else{const Q=setInterval(()=>{W.revalidate()},5e3),me=setTimeout(()=>{clearInterval(Q)},3e4);return()=>{clearInterval(Q),clearTimeout(me)}}},[Me,lt,W]);const vt=(Q,me)=>Q==="scenarios"?`/entity/${d?.sha}/scenarios`:`/entity/${d?.sha}/${Q}`,Xt=(Q,me)=>`/entity/${d?.sha}/scenarios/${Q}/${me}`,Ct=Q=>{I(Q),E?.id&&x(Xt(E.id,Q),{replace:!0})},Nt=d?zn(d):!1,en=m!==null;return n(Jt,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("button",{onClick:v,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-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:d?.name}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d?.filePath,children:d?.filePath})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:it?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Be,{size:14,className:"animate-spin"}),"Analyzing..."]}):ye?c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#f3e5f5] border border-[#ce93d8] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#9c27b0]"}),n("span",{className:"text-xs font-semibold text-[#6a1b9a]",children:"Queued"})]}):en?Nt?c(re,{children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#e3f2fd] border border-[#90caf9] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#2196f3]"}),n("span",{className:"text-xs font-semibold text-[#1976d2]",children:"Out of date"})]}),n("button",{onClick:Ve,disabled:ue.state!=="idle",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 disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})]}):c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#e8f5e9] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#4caf50]"}),n("span",{className:"text-xs font-semibold text-[#2e7d32]",children:"Up to date"})]}):c(re,{children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{onClick:Ve,disabled:ue.state!=="idle",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 disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})]})})]})}),n("div",{className:"bg-[#efefef] border-b border-[#e1e1e1] shrink-0",children:n("div",{className:"flex items-center gap-6 h-10 px-[15px] shrink-0",children:[{id:"scenarios",label:"Scenarios",count:w.length},{id:"related",label:"Related Entities",count:h.importedEntities.length+h.importingEntities.length},{id:"data",label:"Data Structure"},{id:"code",label:"Code"},{id:"history",label:"History"}].map(Q=>c(Z,{to:vt(Q.id),className:`flex items-center justify-center gap-3 shrink-0 text-sm rounded-md transition-colors no-underline ${N===Q.id?"bg-[#343434] text-[#efefef] font-medium h-8 px-6":"text-[#3e3e3e] font-normal hover:bg-gray-100 py-1 px-[15px]"}`,children:[Q.label,Q.count!==void 0&&n("span",{className:`w-[25px] h-5 rounded-md text-xs font-normal flex items-center justify-center ${N===Q.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:Q.count})]},Q.id))})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[N==="scenarios"&&c(re,{children:[n(Qc,{scenarios:w,analysis:m,selectedScenario:E,entitySha:d?.sha||"",cacheBuster:O,activeTab:N,entityType:d?.entityType,entity:d,queueState:b,processIsRunning:S,viewMode:A,setViewMode:Ct,onDebugSetup:()=>{!E?.id||!m?.id||B.submit({analysisId:m.id,scenarioId:E.id},{method:"post",action:"/api/debug-setup"})},debugFetcher:B}),n(ua,{selectedScenario:E,analysis:m,entity:d,viewMode:A,cacheBuster:O,hasScenarios:w.length>0,isAnalyzing:lt,projectSlug:u,hasAnApiKey:y})]}),N==="related"&&n(od,{relatedEntities:h}),N==="data"&&n(dd,{entity:d,analysis:m,scenarios:w,onAnalyze:Ve}),N==="code"&&n(fd,{entity:d,entityCode:p}),N==="history"&&n(rd,{entity:d,history:f})]}),$&&u&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>U(!1),children:c("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:Q=>Q.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>U(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(rt,{projectSlug:u,onClose:()=>U(!1)})})]})}),q&&J&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>K(!1),children:c("div",{className:"bg-white rounded-xl max-w-[800px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:Q=>Q.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("div",{className:"flex items-center gap-3",children:n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:J.instructions?.title||"Debug Environment Ready"})}),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:()=>K(!1),children:"×"})]}),n("div",{className:"px-6 py-6 overflow-y-auto flex-1",children:n("div",{className:"p-0",children:J.instructions?.sections?.map((Q,me)=>c("div",{className:"mb-6 last:mb-0",children:[c("h3",{className:"text-base font-semibold text-gray-900 m-0 mb-3 pb-2 border-b-2 border-gray-200 flex items-center gap-2",children:[Q.heading==="Status"&&!J.complete&&n("div",{className:"w-6 h-6 border-3 border-purple-600 border-t-transparent rounded-full animate-spin",style:{borderWidth:"3px"}}),Q.heading]}),Q.items.map((de,xe)=>c("div",{className:"mb-3 pl-0 last:mb-0",children:[de.label&&n("div",{className:"font-semibold text-gray-700 mb-1 text-sm",children:de.label}),de.isCode?c("div",{className:"relative mt-1",children:[n("code",{className:"block bg-gray-800 text-gray-50 px-3 py-2.5 pr-[90px] rounded-md text-[13px] font-mono overflow-x-auto",children:de.content}),n(xn,{content:de.content,label:"📋 Copy",className:"absolute top-2 right-2 px-2.5 py-1 bg-purple-600/90 text-white border-none rounded text-[11px] font-semibold cursor-pointer transition-all backdrop-blur hover:bg-purple-700/95 hover:scale-105 active:scale-95 disabled:opacity-75 disabled:cursor-not-allowed disabled:scale-100"})]}):de.isLink?c("div",{className:"flex items-center gap-2 mt-1",children:[n("a",{href:de.content,target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-800 underline text-sm font-medium",children:de.content}),n(xn,{content:de.content,label:"📋",className:"px-2 py-1 bg-gray-200 text-gray-700 border-none rounded text-[11px] font-semibold cursor-pointer transition-all hover:bg-gray-300 hover:scale-105 active:scale-95"})]}):n("div",{className:"text-gray-600 text-sm leading-relaxed",children:de.content})]},xe))]},me))})}),n("div",{className:"px-6 py-6 border-t border-gray-200 flex justify-end gap-3",children:n("button",{className:"px-5 py-2.5 bg-gray-500 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-gray-600",onClick:()=>K(!1),children:"Close"})})]})})]})})}),wd=Object.freeze(Object.defineProperty({__proto__:null,default:bd,loader:xd,meta:gd,shouldRevalidate:yd},Symbol.toStringTag,{value:"Module"}));async function vd(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 we();const i=ie();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=le.join(i,".codeyam","config.json"),d=JSON.parse(await ge.readFile(l,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const h=`/tmp/codeyam/local-dev/${m}/codeyam/log.txt`;try{await ge.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ee(m);let g=r;if(!g||g.length===0){console.log("[analyzeEntities] Loading entities to determine file paths...");const w=await et({shas:t});if(!w||w.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);g=[...new Set(w.map(x=>x.filePath).filter(x=>!!x))],console.log(`[analyzeEntities] Found ${g.length} unique files`)}if(!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const y=await Io(p,f,g);console.log(`[analyzeEntities] Created commit ${y.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Qe({commitSha:y.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),currentEntityShas:t,entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(w,x)=>{if(!w)return;const C=w.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&Ol(w)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:y.sha,projectSlug:m,filePaths:g,entityShas:t,...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${b} for ${t.length} entities`),{jobId:b}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Cd({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await De()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(s)m=[s];else return D({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return D({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const{jobId:u}=await vd({entityShas:m,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${u}`),D({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,jobId:u})}catch(a){return console.error("[API] Error starting analysis:",a),D({error:"Failed to start analysis",details:a.message},{status:500})}}const Nd=Object.freeze(Object.defineProperty({__proto__:null,action:Cd},Symbol.toStringTag,{value:"Module"}));function Sd({entity:e,variant:t="default"}){const r=Yn(e),{badge:a,hasOutdatedSimulations:s}=r;return t==="compact"?s?n("div",{className:"bg-yellow-50 px-2 py-1 rounded text-[10px] font-medium text-yellow-700",children:"Out of date"}):c("div",{className:"flex items-center gap-1.5 bg-green-50 px-2 py-1 rounded text-[10px] font-medium text-green-700",children:[n("div",{className:"w-2 h-2 rounded-full bg-green-500"}),"Up to date"]}):c("div",{className:`flex items-center gap-2 px-[15px] py-0 h-[26px] ${a.bgColor} rounded`,children:[n("div",{className:`w-2 h-2 rounded-full ${s?"bg-amber-500":"bg-green-500"}`}),n("span",{className:`text-xs font-semibold ${a.color}`,children:s?"Out of date":"Up to date"})]})}const Ad="data:image/svg+xml,%3csvg%20width='35'%20height='35'%20viewBox='0%200%2035%2035'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='35'%20height='35'%20rx='4'%20fill='%239040F5'/%3e%3cpath%20d='M26.6995%2024.0683V18.306L21.2533%2012.835L14.5785%2019.5423L12.4946%2017.4919L8.29688%2021.6596V24.0683H26.6995Z'%20fill='%23F3EEFE'/%3e%3ccircle%20cx='12.4044'%20cy='13.4307'%20r='2.49813'%20fill='%23F3EEFE'/%3e%3c/svg%3e",Ed=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function _d({request:e}){try{const t=await wt();return D({entities:t||[]})}catch(t){return console.error("Failed to load simulations:",t),D({entities:[],error:"Failed to load simulations"})}}const Pd=_e(function(){const r=Ie().entities,[a,s]=k(""),[o,i]=k("visual"),[l,d]=k(null),m=ee(()=>{const N=[];return r.forEach(E=>{const A=E.analyses?.[0];if(A?.scenarios){const I=A.scenarios.filter(T=>T.metadata?.screenshotPaths?.[0]).map(T=>({scenarioName:T.name,scenarioDescription:T.description||"",screenshotPath:T.metadata?.screenshotPaths?.[0]||"",scenarioId:T.id}));I.length>0&&N.push({entity:E,screenshots:I,createdAt:A.createdAt||""})}}),N.sort((E,A)=>new Date(A.createdAt).getTime()-new Date(E.createdAt).getTime()),N},[r]),u=ee(()=>r.filter(N=>!N.analyses?.[0]?.scenarios?.some(I=>I.metadata?.screenshotPaths?.[0])),[r]),h=ee(()=>m.filter(({entity:N})=>{const E=!a||N.name.toLowerCase().includes(a.toLowerCase()),A=o==="all"||N.entityType===o;return E&&A}),[m,a,o]),p=ee(()=>u.filter(N=>{const E=!a||N.name.toLowerCase().includes(a.toLowerCase()),A=o==="all"||N.entityType===o;return E&&A}),[u,a,o]),f=ee(()=>{const N=[];return h.forEach(({entity:E,screenshots:A})=>{A.forEach(I=>{N.push({entitySha:E.sha,entityName:E.name,scenarioId:I.scenarioId||"",scenarioName:I.scenarioName,scenarioDescription:I.scenarioDescription,screenshotPath:I.screenshotPath})})}),N},[h]),g=V(N=>{s(N.target.value)},[]),y=V(N=>{i(N.target.value)},[]),b=V((N,E)=>{const A=f.findIndex(I=>I.entitySha===N&&I.scenarioId===E);A!==-1&&d(A)},[f]),w=V(()=>{d(null)},[]),x=V(()=>{d(N=>N===null||N===0?f.length-1:N-1)},[f.length]),C=V(()=>{d(N=>N===null?0:(N+1)%f.length)},[f.length]);G(()=>{if(l===null)return;const N=E=>{E.key==="Escape"?w():E.key==="ArrowLeft"?x():E.key==="ArrowRight"&&C()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[l,w,x,C]);const v=m.length>0,S=l!==null?f[l]:null;return c("div",{className:"bg-[#f9f9f9] min-h-screen overflow-y-auto",children:[c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 m-0",children:"Simulations"}),n("p",{className:"text-sm text-gray-600 mt-2",children:"All recently captured simulations."})]}),!v&&c("div",{className:"rounded-lg px-5 py-6 mb-6 flex items-center gap-4",style:{backgroundColor:"#f3eefe"},children:[n("img",{src:Ad,alt:"",className:"rounded shrink-0",style:{width:"35px",height:"35px"}}),c("div",{children:[n("p",{className:"text-sm m-0 mb-1",style:{color:"#9040f5"},children:"This page will display a visual gallery of your recently captured component screenshots."}),n("p",{className:"text-sm font-semibold m-0",style:{color:"#9040f5"},children:"Start by analyzing your first component below."})]})]}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[10px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 py-2 pr-8 text-sm cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:o,onChange:y,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(hn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Er,{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 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:g})]})]})]}),c("div",{className:"flex flex-col gap-3",children:[v&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):c(re,{children:[h.map(({entity:N,screenshots:E})=>n(Td,{entity:N,screenshots:E,onScreenshotClick:b},N.sha)),n("div",{className:"bg-white border-x border-b border-gray-200 rounded-b-lg px-5 py-4 text-center",children:n(Z,{to:"/files?entityType=visual",className:"text-sm text-[#005c75] hover:text-[#004a5e] hover:underline",children:"Find more entities to simulate →"})})]})),!v&&(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(N=>n(kd,{entity:N},N.sha)))]})]}),S&&n(Md,{screenshot:S,currentIndex:l,totalCount:f.length,onClose:w,onPrevious:x,onNext:C})]})});function Md({screenshot:e,currentIndex:t,totalCount:r,onClose:a,onPrevious:s,onNext:o}){const i=tt(),[l,d]=k(!1),m=()=>{i(`/entity/${e.entitySha}/scenarios/${e.scenarioId}?from=simulations`)};return n("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",onClick:a,children:c("div",{className:"relative flex flex-col w-[90vw] h-[90vh] max-w-[1400px] bg-white rounded-lg overflow-hidden",onClick:u=>u.stopPropagation(),children:[c("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 bg-gray-50 shrink-0",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-sm text-gray-500",children:[t+1," of ",r]}),n("span",{className:"text-gray-300",children:"|"}),n("span",{className:"text-sm font-medium text-gray-700",children:e.entityName})]}),n("button",{onClick:a,className:"p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-200 rounded-full transition-colors cursor-pointer",children:n(Da,{className:"w-5 h-5"})})]}),c("div",{className:"relative flex-1 flex items-center justify-center p-6 bg-gray-100 overflow-hidden",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[n("button",{onClick:s,className:`absolute left-4 z-10 p-3 bg-white/90 hover:bg-white rounded-full shadow-lg transition-all cursor-pointer ${l?"opacity-100":"opacity-0"}`,children:n(La,{className:"w-6 h-6 text-gray-700"})}),n("div",{className:"flex items-center justify-center w-full h-full cursor-pointer",onClick:m,children:n(be,{screenshotPath:e.screenshotPath,alt:e.scenarioName,className:"max-w-full max-h-full object-contain rounded-lg shadow-lg"})}),n("button",{onClick:o,className:`absolute right-4 z-10 p-3 bg-white/90 hover:bg-white rounded-full shadow-lg transition-all cursor-pointer ${l?"opacity-100":"opacity-0"}`,children:n(Gn,{className:"w-6 h-6 text-gray-700"})})]}),c("div",{className:"px-6 py-4 border-t border-gray-200 bg-white cursor-pointer hover:bg-gray-50 transition-colors shrink-0",onClick:m,children:[c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-lg font-semibold text-[#005c75] hover:text-[#004a5e] m-0 mb-1",children:e.scenarioName}),n("p",{className:"text-sm text-gray-600 m-0 line-clamp-2 min-h-10",children:e.scenarioDescription||" "})]}),c("div",{className:"shrink-0 flex items-center gap-1 text-sm text-[#005c75]",children:[n("span",{children:"View details"}),n(Gn,{className:"w-4 h-4"})]})]}),n("p",{className:"text-xs text-gray-400 mt-2 m-0",children:"Click to view this scenario in the entity page"})]})]})})}function Td({entity:e,screenshots:t,onScreenshotClick:r}){const a=tt();e.entityType;const s=t.length||(e.analyses?.[0]?.scenarios?.length??0),o=i=>{a(`/entity/${e.sha}/scenarios/${i}?from=simulations`)};return n("div",{className:"bg-white border-x border-b border-gray-200 first:border-t last:rounded-b-lg hover:bg-gray-100 transition-colors",children:c("div",{className:"px-5 py-4",children:[c("div",{className:"flex items-center justify-between",children:[c(Z,{to:`/entity/${e.sha}`,className:"flex items-center gap-2 no-underline",children:[n(Fe,{type:e.entityType}),c("span",{className:"text-xs font-medium text-gray-800",children:[e.name," (",s,")"]})]}),n(Sd,{entity:e,variant:"compact"})]}),n("div",{className:"flex gap-2.5 mt-3 overflow-x-auto pb-1",children:t.length>0?t.map(i=>n("button",{onClick:()=>o(i.scenarioId||""),className:"shrink-0 block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border border-gray-200 overflow-hidden bg-gray-100 flex items-center justify-center transition-all",style:{"--hover-border":"#005C75"},onMouseEnter:l=>{l.currentTarget.style.borderColor="#005C75",l.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)"},onMouseLeave:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none"},children:n(be,{screenshotPath:i.screenshotPath,alt:i.scenarioName,className:"max-w-full max-h-full object-contain"})})},i.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function kd({entity:e}){const t=fe(),[r,a]=k(!1);e.entityType;const s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};G(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]);const o=i=>{if(!i)return"";const l=new Date(i),d=new Date;return l.toDateString()===d.toDateString()?`Today, ${l.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0}).toLowerCase()}`:l.toLocaleDateString("en-US",{month:"short",day:"numeric"})};return n("div",{className:"bg-white border-x border-b border-gray-200 first:border-t last:rounded-b-lg hover:bg-gray-100 transition-colors cursor-pointer",onClick:s,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Fe,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(Z,{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:o(e.createdAt)}),n("div",{className:"w-24 flex justify-end",children:n("button",{onClick:s,disabled:r||t.state!=="idle",className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Analyzing...":"Analyze"})})]})})}const Id=Object.freeze(Object.defineProperty({__proto__:null,default:Pd,loader:_d,meta:Ed},Symbol.toStringTag,{value:"Module"}));function Rd({request:e,context:t}){const r=t.dbNotifier;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context!"),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"})}
|
|
160
|
+
|
|
161
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
162
|
+
|
|
163
|
+
`))}catch{l()}};r.on("change",d);const m=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
164
|
+
|
|
165
|
+
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const $d=Object.freeze(Object.defineProperty({__proto__:null,loader:Rd},Symbol.toStringTag,{value:"Module"}));function Ue(){const e=process.memoryUsage(),t=fs.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(pn.totalmem()/1024/1024),freeMemory:Math.round(pn.freemem()/1024/1024)}}}function jd(){const e=Ue();console.log(`
|
|
166
|
+
[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 Dd(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Ue();global.gc();const t=Ue(),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 Ld(){const e=Ue(),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 Od({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=Dd(),s=Ue();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=jd();return Response.json({success:!0,stats:a})}case"leaks":{const a=Ld(),s=Ue();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=Ue();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory?action=detailed - Log detailed stats to console",leaks:"/api/memory?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 Fd=Object.freeze(Object.defineProperty({__proto__:null,loader:Od},Symbol.toStringTag,{value:"Module"}));async function Yd({request:e,context:t}){let r=t.analysisQueue;if(r||(r=await De()),!r)return D({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return D({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const o=a.searchParams.get("jobId");if(!o)return D({error:"Missing jobId parameter for job query"},{status:400});const i=r.getState();if(i.currentlyExecuting?.id===o)return D({jobId:o,status:"running",job:i.currentlyExecuting});const l=i.jobs.find(m=>m.id===o);if(l){const m=i.jobs.indexOf(l);return D({jobId:o,status:"queued",position:m,job:l})}const d=r.getJobResult(o);return d?D({jobId:o,status:d.status==="error"?"failed":"completed",error:d.error}):D({jobId:o,status:"completed"})}if(s==="full"){const o=r.getState(),i=await Promise.all(o.jobs.map(async d=>{const m=[];if(d.entityShas&&d.entityShas.length>0){const u=d.entityShas.map(p=>Re(p)),h=await Promise.all(u);m.push(...h.filter(p=>p!==null))}return{id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:m,filePaths:d.filePaths}}));let l;if(o.currentlyExecuting){const d=o.currentlyExecuting,m=[];if(d.entityShas&&d.entityShas.length>0){const u=d.entityShas.map(p=>Re(p)),h=await Promise.all(u);m.push(...h.filter(p=>p!==null))}l={id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:m,filePaths:d.filePaths}}return D({state:{...o,jobsWithEntities:i,currentlyExecutingWithEntities:l}})}return D({error:"Unknown queryType"},{status:400})}async function zd({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?.analysisQueue);let r=t.analysisQueue;if(r||(r=await De(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),D({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:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),D({jobId:i,status:"queued"})}return s==="resume"?(r.resume(),D({status:"resumed"})):s==="pause"?(r.pause(),D({status:"paused"})):D({error:"Unknown action"},{status:400})}const Bd=Object.freeze(Object.defineProperty({__proto__:null,action:zd,loader:Yd},Symbol.toStringTag,{value:"Module"})),Ud=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],qd=_e(function(){return fe(),n(Jt,{children:c("div",{className:"h-screen bg-[#f9f9f9] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(ua,{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})]})]})})}),Wd=Object.freeze(Object.defineProperty({__proto__:null,default:qd,meta:Ud},Symbol.toStringTag,{value:"Module"})),Gd=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function Hd({request:e}){try{const t=await Wr();if(!t)return D({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=ie()||process.cwd(),a=await Vt(r),s=Ql(t.projectSlug);return D({config:t,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:s,error:null})}catch(t){return console.error("Failed to load config:",t),D({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}async function Kd({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("groqApiKey"),s=t.get("anthropicApiKey"),o=t.get("openAiApiKey"),i=t.get("pathsToIgnore");let l;if(r)try{l=JSON.parse(r)}catch{return D({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let d;if(i&&(d=i.split(",").map(h=>h.trim()).map(h=>h.startsWith('"')&&h.endsWith('"')||h.startsWith("'")&&h.endsWith("'")?h.slice(1,-1):h).filter(h=>h.length>0)),!await Kr({universalMocks:l,pathsToIgnore:d}))return D({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let u=!1;if(a!==void 0||s!==void 0||o!==void 0){const h=ie()||process.cwd(),p=await Vt(h);u=a!==void 0&&a!==(p.GROQ_API_KEY||"")||s!==void 0&&s!==(p.ANTHROPIC_API_KEY||"")||o!==void 0&&o!==(p.OPENAI_API_KEY||""),await $o(h,{...p,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:o||void 0},!0)}return D({success:!0,error:null,requiresRestart:u})}catch(t){return console.log("[Settings Action] Failed to save config:",t),D({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Vd(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function xr({mock:e,onSave:t,onCancel:r}){const[a,s]=k(e.entityName),[o,i]=k(e.filePath),[l,d]=k(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value: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-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., packages/supabase/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange: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-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:l})},className:"px-4 py-2 bg-blue-600 text-white border-none rounded text-sm cursor-pointer hover:bg-blue-700",children:"Save"})]})]})}function Jd(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Qd=_e(function(){const{config:t,secrets:r,versionInfo:a,error:s}=Ie(),o=Na(),i=fe(),l=nt(),[d,m]=k(t?.universalMocks||[]),[u,h]=k((t?.pathsToIgnore||[]).join(", ")),[p,f]=k((t?.pathsToIgnore||[]).join(", ")),[g,y]=k(r?.GROQ_API_KEY||""),[b,w]=k(r?.ANTHROPIC_API_KEY||""),[x,C]=k(r?.OPENAI_API_KEY||""),[v,S]=k(!1),[N,E]=k(!1),[A,I]=k(!1),[T,M]=k(!1),[P,L]=k(!1),[_,R]=k(!1),[O,Y]=k(null),[J,F]=k(!1);G(()=>{if(t){m(t.universalMocks||[]);const j=(t.pathsToIgnore||[]).join(", ");h(j),f(j)}r&&(y(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),C(r.OPENAI_API_KEY||""))},[t,r]),G(()=>{if(o?.success){M(!0);const j=setTimeout(()=>M(!1),3e3);return()=>clearTimeout(j)}},[o]),G(()=>{if(i.state==="idle"&&i.data&&!_){console.log("[Settings] Fetcher data:",i.data);const j=i.data;if(j.success){console.log("[Settings] Save successful, revalidating..."),M(!0),R(!0),(u!==p||j.requiresRestart)&&L(!0),l.revalidate();const B=setTimeout(()=>{M(!1),R(!1)},3e3);return()=>clearTimeout(B)}}},[i.state,i.data,_,l,u,p]);const q=j=>{j.preventDefault();const B=new FormData(j.currentTarget);B.set("universalMocks",JSON.stringify(d)),console.log("[Settings] Submitting form data:",{universalMocks:B.get("universalMocks"),openAiApiKey:B.get("openAiApiKey")?"***":"(empty)"}),i.submit(B,{method:"post"})},K=j=>{m([...d,j]),F(!1)},$=(j,B)=>{const te=[...d];te[j]=B,m(te),Y(null)},U=j=>{m(d.filter((B,te)=>te!==j))};return s?c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:s})})]}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Settings"}),n("p",{className:"text-sm text-gray-500 mt-2",children:"Project Configuration"})]}),n("div",{className:"max-w-5xl my-8",children:c("form",{onSubmit:q,className:"space-y-6",children:[c("div",{children:[n("h2",{className:"text-xl mb-4 text-gray-800 font-semibold",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t?.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((j,B)=>n("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded",children:c("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:j.path==="."?"Root":j.path})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:j.framework})]}),j.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:j.appDirectory})]}),j.startCommand&&c("div",{className:"col-span-2",children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[j.startCommand.command," ",j.startCommand.args?.join(" ")]})]})]})},B))}):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`."})]}),c("div",{className:"mb-8",children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider Configuration"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:v?"text":"password",id:"groqApiKey",name:"groqApiKey",value:g,onChange:j=>y(j.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-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>S(!v),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",children:v?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:N?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:b,onChange:j=>w(j.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-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>E(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none",children:N?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:x,onChange:j=>C(j.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-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>I(!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",children:A?"Hide":"Show"})]})]})]})]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"pathsToIgnore",className:"block mb-2 font-medium text-gray-700",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:u,onChange:j=>h(j.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-base font-mono focus:outline-none focus:border-blue-600 focus:ring-2 focus:ring-blue-600/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),c("div",{className:"mb-6",children:[c("div",{className:"flex justify-between items-center mb-3",children:[n("label",{className:"block font-medium text-gray-700",children:"Universal Mocks"}),n("button",{type:"button",onClick:()=>F(!0),className:"px-4 py-2 bg-green-600 text-white border-none rounded text-sm cursor-pointer hover:bg-green-700",children:"Add Mock"})]}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),d.length===0?n("div",{className:"p-4 bg-gray-50 rounded text-sm text-gray-500 text-center",children:"No universal mocks configured"}):n("div",{className:"space-y-3",children:d.map((j,B)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:O===B?n(xr,{mock:j,onSave:te=>$(B,te),onCancel:()=>Y(null)}):n(re,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:j.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:j.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:j.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(B),className:"px-3 py-1 bg-blue-600 text-white border-none rounded text-sm cursor-pointer hover:bg-blue-700",children:"Edit"}),n("button",{type:"button",onClick:()=>U(B),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},B))})]})]}),c("div",{className:"flex gap-4 items-center",children:[n("button",{type:"submit",disabled:i.state==="submitting",className:"px-8 py-3 bg-blue-600 text-white border-none rounded text-base font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-blue-700 whitespace-nowrap",children:i.state==="submitting"?"Saving...":"Save Settings"}),i.state==="submitting"&&n("span",{className:"text-gray-600 text-sm font-medium",children:"Saving..."}),T&&n("span",{className:"text-emerald-600 text-sm font-medium whitespace-nowrap",children:"Settings saved successfully!"}),P&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-3 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"})]}),o?.error&&n("span",{className:"text-red-600 text-sm font-medium",children:o.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const j=i.data;return typeof j.error=="string"?n("span",{className:"text-red-600 text-sm font-medium",children:j.error}):null}return null})()]}),t&&c("div",{className:"mt-8 p-4 bg-gray-50 rounded text-sm",children:[n("h3",{className:"text-base mb-3 text-gray-800 font-semibold",children:"Current Configuration"}),c("dl",{className:"grid grid-cols-[150px_1fr] gap-2 m-0",children:[t.projectSlug&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Project Slug:"}),n("dd",{className:"m-0 text-gray-800",children:t.projectSlug})]}),t.packageManager&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Package Manager:"}),n("dd",{className:"m-0 text-gray-800",children:t.packageManager})]}),t.webapps&&t.webapps.length>0&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Web Applications:"}),n("dd",{className:"m-0 text-gray-800",children:t.webapps.map((j,B)=>c("div",{className:"mb-2",children:[n("div",{className:"font-semibold",children:j.path==="."?"Root":j.path}),c("div",{className:"text-sm text-gray-600",children:["Framework: ",j.framework]}),j.startCommand&&c("div",{className:"text-sm text-gray-600 font-mono",children:["Command:"," ",Vd(j.startCommand)]})]},B))})]})]})]}),a&&c("div",{className:"mt-8 p-4 bg-gray-50 rounded text-sm",children:[n("h3",{className:"text-base mb-3 text-gray-800 font-semibold",children:"Version Information"}),c("dl",{className:"grid grid-cols-[180px_1fr] gap-2 m-0",children:[a.webserverVersion&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Webserver:"}),n("dd",{className:"m-0 text-gray-800 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Analyzer Template:"}),c("dd",{className:"m-0 text-gray-800",children:[n("span",{className:"font-mono",children:a.templateVersion.version||a.templateVersion.gitCommit?.slice(0,7)||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",Jd(a.templateVersion.buildTimestamp),")"]})]})]}),a.cachedAnalyzerVersion&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Cached Analyzer:"}),c("dd",{className:"m-0 text-gray-800",children:[n("span",{className:"font-mono",children:a.cachedAnalyzerVersion.version||a.cachedAnalyzerVersion.gitCommit?.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?.projectSlug&&c(re,{children:[n("dt",{className:"font-medium text-gray-600",children:"Cached Analyzer:"}),n("dd",{className:"m-0 text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})]})]})}),J&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(xr,{mock:{entityName:"",filePath:"",content:""},onSave:K,onCancel:()=>F(!1)})]})})]})})}),Zd=Object.freeze(Object.defineProperty({__proto__:null,action:Kd,default:Qd,loader:Hd,meta:Gd},Symbol.toStringTag,{value:"Module"}));async function Xd({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=ie();if(!r)return new Response("Project root not found",{status:500});const s=le.extname(t)!==""?t:`${t}.html`,o=le.join(r,".codeyam","captures","static",s);try{await ge.access(o);let i=await ge.readFile(o);const l=le.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let m=i.toString("utf-8");const u=m.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;m=m.replace(u[0],g)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(m,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const eu=Object.freeze(Object.defineProperty({__proto__:null,loader:Xd},Symbol.toStringTag,{value:"Module"}));function ma(e,t,r=10){const a=new Map,s=d=>d.entityType==="visual"||d.entityType==="library";for(const d of e)s(d)&&a.set(d.sha,{entity:d,depth:0});const o=new Map;for(const d of t){const m=d.metadata?.importedBy;if(m)for(const u of Object.keys(m))for(const h of Object.keys(m[u])){const{shas:p}=m[u][h];for(const f of p)o.has(d.sha)||o.set(d.sha,new Set),o.get(d.sha).add(f)}}const i=[],l=new Set;for(const d of e)i.push({sha:d.sha,depth:0}),l.add(d.sha);for(;i.length>0;){const{sha:d,depth:m}=i.shift();if(m>=r)continue;const u=o.get(d);if(u)for(const h of u){if(l.has(h))continue;l.add(h);const p=t.find(f=>f.sha===h);if(p){if(s(p)){const f=m+1,g=a.get(h);(!g||f<g.depth)&&a.set(h,{entity:p,depth:f})}i.push({sha:h,depth:m+1})}}}return Array.from(a.values()).sort((d,m)=>d.depth!==m.depth?d.depth-m.depth:d.entity.name.localeCompare(m.entity.name))}function qt(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)=>{const l=o.metadata?.editedAt||o.createdAt||"";return(i.metadata?.editedAt||i.createdAt||"").localeCompare(l)});r.push(s[0])}return r}function ha(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=>a.has(d.filePath)&&d.metadata?.isUncommitted&&!d.metadata?.isSuperseded),l=qt(i);r.set(s.path,{status:s,entities:o,editedEntities:l})}return r}function tu(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),l=qt(i);a.set(o.path,{status:o,entities:l})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&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 l=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],d=qt(l);a.set(o.path,{status:o,entities:d})}}return a}function nu(e,t){const r=new Map,a=pa(e,t);for(const s of a){const i=ma([s],t).filter(({depth:l})=>l>0);r.set(s.sha,i)}return r}function ru(e,t){const r=new Map;for(const a of e){const o=ma([a],t).filter(({depth:i})=>i>0);r.set(a.sha,o)}return r}function pa(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=>r.has(s.filePath)&&s.metadata?.isUncommitted&&!s.metadata?.isSuperseded);return qt(a)}const au=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function su({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},[s,o,i]=await Promise.all([wt(),Pe(),Ke()]),l=ra(),d=s?ha(l,s):new Map,m=Array.from(d.entries()).sort((A,I)=>A[0].localeCompare(I[0])),u=s?.length||0,h=s?.filter(A=>A.entityType==="visual").length||0,p=s?.filter(A=>A.entityType==="library").length||0,f=s?pa(l,s):[],g=f.length,y=s?.filter(A=>(A.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length||0,b=s?.reduce((A,I)=>{const T=I.analyses?.[0]?.scenarios?.length||0;return A+T},0)||0,w=s?.reduce((A,I)=>{const M=(I.analyses?.[0]?.scenarios||[]).filter(P=>P.metadata?.screenshotPaths?.[0]).length;return A+M},0)||0,x=[];s?.forEach(A=>{const I=A.analyses?.[0];I?.scenarios&&I.scenarios.forEach(T=>{const M=T.metadata?.screenshotPaths?.[0];M&&x.push({entitySha:A.sha,entityName:A.name,scenarioId:T.id,scenarioName:T.name,screenshotPath:M,createdAt:I.createdAt||""})})}),x.sort((A,I)=>new Date(I.createdAt).getTime()-new Date(A.createdAt).getTime());const C=x.slice(0,16),v=s?.filter(A=>A.entityType==="visual").filter(A=>!A.analyses?.[0]?.scenarios?.some(M=>M.metadata?.screenshotPaths?.[0])).slice(0,8)||[],N=i?.metadata?.currentRun?.currentEntityShas?.length||0,E=a.jobs.length||0;return D({stats:{totalEntities:u,visualEntities:h,libraryEntities:p,uncommittedEntities:g,entitiesWithAnalyses:y,totalScenarios:b,capturedScreenshots:w,currentlyAnalyzing:N,filesOnQueue:E},uncommittedFiles:m,uncommittedEntitiesList:f,recentSimulations:C,visualEntitiesForSimulation:v,projectSlug:o,queueState:a,currentCommit:i})}catch(r){return console.error("Failed to load dashboard data:",r),D({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 ou=_e(function(){const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=Ie(),m=fe(),u=nt(),{showToast:h}=_n(),[p,f]=k(new Set),[g,y]=k(null),[b,w]=k(!1),[x,C]=k(!1),{lastLine:v,isCompleted:S,resetLogs:N}=Ye(i,!!g),{simulatingEntity:E,scenarios:A,scenarioStatuses:I,allScenariosCaptured:T}=ee(()=>{const $={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return $;const U=o?.find(ne=>ne.sha===g);if(!U)return $;const j=U.analyses?.[0],B=j?.scenarios||[],te=j?.status?.scenarios||[],ue=te.filter(ne=>ne.screenshotFinishedAt).length,W=B.length>0&&ue===B.length;return{simulatingEntity:U,scenarios:B,scenarioStatuses:te,allScenariosCaptured:W}},[g,o]);G(()=>{(S||T)&&y(null)},[S,T]);const M=d?.metadata?.currentRun,P=new Set(M?.currentEntityShas||[]),L=new Set(l.jobs.flatMap($=>$.entityShas||[])),_=new Set(l.currentlyExecuting?.entityShas||[]),R=a.filter($=>$.entityType==="visual"||$.entityType==="library"),O=R.filter($=>!P.has($.sha)&&!L.has($.sha)&&!_.has($.sha)),Y=()=>{if(O.length===0){h("All entities are already queued or analyzing","info",3e3);return}console.log("Analyzing uncommitted entities not yet queued:",O.length),console.log("Entity SHAs:",O.map($=>$.sha)),C(!0),h(`Starting analysis for ${O.length} entities...`,"info",3e3),m.submit({entityShas:O.map($=>$.sha).join(",")},{method:"post",action:"/api/analyze"})};G(()=>{if(m.state==="idle"&&m.data){const $=m.data;$.success?(console.log("[Analyze All] Success:",$.message),h(`Analysis started for ${$.entityCount} entities in ${$.fileCount} files. Watch the logs for progress.`,"success",6e3),C(!1)):$.error&&(console.error("[Analyze All] Error:",$.error),h(`Error: ${$.error}`,"error",8e3),C(!1))}},[m.state,m.data,h]);const J=($,U)=>{console.log("Simulating entity:",$);const j=o?.find(B=>B.sha===$);y($),N(),h(`Starting analysis for ${j?.name||"entity"}...`,"info",3e3),m.submit({entitySha:$,filePath:U},{method:"post",action:"/api/analyze"})},F=$=>{f(U=>{const j=new Set(U);return j.has($)?j.delete($):j.add($),j})},q=ee(()=>{const $=new Map;return s.forEach(U=>{const j=U.entitySha;$.has(j)||$.set(j,[]),$.get(j).push(U)}),Array.from($.entries()).map(([U,j])=>({entitySha:U,entityName:j[0].entityName,scenarios:j}))},[s]),K=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#F59E0B"},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981"},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6"},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9"}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"py-6 px-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[n("div",{children:n("h1",{className:"text-3xl font-bold text-gray-900 m-0 mb-2",children:"CodeYam"})}),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:K.map(($,U)=>n(Z,{to:$.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg hover:-translate-y-0.5 no-underline",style:{borderLeft:`4px solid ${$.color}`},children:c("div",{className:"px-6 py-4 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[n("div",{className:"text-xs text-gray-700 font-medium",children:$.label}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 hidden md:flex",style:{color:$.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none flex-shrink-0",style:{backgroundColor:`${$.color}15`},children:[$.iconType==="folder"&&n(Oa,{size:20,style:{color:$.color}}),$.iconType==="check"&&n($t,{size:20,style:{color:$.color}}),$.iconType==="image"&&n(dt,{size:20,style:{color:$.color}}),$.iconType==="gear"&&n(jt,{size:20,style:{color:$.color}}),$.iconType==="code-xml"&&n(Ar,{size:20,style:{color:$.color}})]}),n("div",{className:"text-2xl font-bold text-gray-900 leading-none",children:$.value})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:$.color},children:"View All →"})]})]})},U))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),R.length>0&&n("button",{onClick:Y,disabled:m.state!=="idle"||x||O.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:m.state!=="idle"||x?"Starting analysis...":O.length===0?"All Queued":`Analyze All (${O.length})`})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([$,U])=>{const j=p.has($),B=U.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>F($),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:j?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:$}),c("span",{className:"text-xs text-gray-500",children:[B.length," entit",B.length!==1?"ies":"y"]})]})]})}),j&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:B.length>0?B.map(te=>{const ue=P.has(te.sha),W=L.has(te.sha)||_.has(te.sha);return c(Z,{to:`/entity/${te.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:ne=>ne.currentTarget.style.borderColor="#005C75",onMouseLeave:ne=>ne.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:te.entityType==="visual"?"#8B5CF615":te.entityType==="library"?"#6366F1":"#EC4899"},children:[te.entityType==="visual"&&n(dt,{size:16,style:{color:"#8B5CF6"}}),te.entityType==="library"&&n(Fa,{size:16,className:"text-white"}),te.entityType==="other"&&n(_r,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:te.name}),te.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),te.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),te.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),te.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:te.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[ue&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Be,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ue&&W&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ue&&!W&&n("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),h(`Starting analysis for ${te.name}...`,"info",3e3),m.submit({entityShas:te.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:ne=>ne.currentTarget.style.backgroundColor="#004560",onMouseLeave:ne=>ne.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},te.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},$)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center bg-gray-50 rounded-lg min-h-[200px] justify-center",children:[c("svg",{width:"52",height:"68",viewBox:"0 0 26 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"mb-4 opacity-40",children:[c("g",{clipPath:"url(#clip0_784_10631)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H18.9423L26.0318 7.14651V31.4562C26.0318 32.8693 24.8863 34.0148 23.4732 34.0148H2.55857C1.14551 34.0148 0 32.8693 0 31.4562V2.55857Z",fill:"#D9D9D9"}),n("path",{d:"M18.9453 7.08081H26.0261L18.9453 0V7.08081Z",fill:"#646464"}),n("line",{x1:"3.92188",y1:"13.3633",x2:"21.7341",y2:"13.3633",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"19.4863",x2:"13.0321",y2:"19.4863",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"25.6016",x2:"21.7341",y2:"25.6016",stroke:"#646464",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10631",children:n("rect",{width:"26",height:"34",fill:"white"})})})]}),n("p",{className:"text-sm font-medium text-gray-400 m-0 mb-2",children:"No Uncommitted Changes."})]})]}),c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),s.length>0&&!g?c(re,{children:[n("div",{className:"space-y-6 mb-5",children:q.map($=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(dt,{size:16,style:{color:"#8B5CF6"}})}),n(Z,{to:`/entity/${$.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:$.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:$.scenarios.map((U,j)=>n(Z,{to:U.scenarioId?`/entity/${U.entitySha}/scenarios/${U.scenarioId}`:`/entity/${U.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:B=>{B.currentTarget.style.borderColor="#005C75",B.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:B=>{B.currentTarget.style.borderColor="#E5E7EB",B.currentTarget.style.boxShadow="none"},title:`${U.scenarioName}`,children:n(be,{screenshotPath:U.screenshotPath,alt:U.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},j))})]},$.entitySha))}),n(Z,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:$=>$.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:$=>$.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):g?c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[E&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Fe,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",E.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:E.filePath})]})]})}),T?c("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),c("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):v?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Be,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:v,children:v}),i&&n("button",{onClick:()=>w(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):m.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Be,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Be,{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(($,U)=>{const j=$.metadata?.screenshotPaths?.[0],B=I.find(W=>W.name===$.name),te=B?.screenshotStartedAt&&!B?.screenshotFinishedAt;return j?n(Z,{to:`/entity/${g}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(be,{screenshotPath:j,alt:$.name,title:$.name,className:"max-w-full max-h-full object-contain object-center"})},U):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:`Capturing ${$.name}...`,children:n("span",{className:te?"animate-pulse":"text-gray-400",children:te?"⋯":"⏹️"})},U)})})]}):c("div",{className:"flex flex-col items-center",children:[c("div",{className:"py-12 px-6 text-center bg-gray-50 rounded-lg w-full flex flex-col items-center justify-center min-h-[200px]",children:[n("div",{className:"mb-4 bg-[#efefef] rounded-lg p-3",children:n(dt,{size:28,style:{color:"#999999"},strokeWidth:1.5})}),n("p",{className:"text-gray-700 m-0 font-semibold",children:"Start by analyzing your first component below."})]}),(o?.length??0)>0?n(re,{children:n("div",{className:"flex flex-col gap-3 mt-6 w-full",children:(g&&E?[E]:o||[]).map($=>n("div",{className:"flex flex-col gap-3",children:c("div",{className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg transition-colors",style:{borderLeft:"4px solid #8B5CF6"},onMouseEnter:U=>{U.currentTarget.style.backgroundColor="#F9FAFB"},onMouseLeave:U=>{U.currentTarget.style.backgroundColor="white"},children:[c(Z,{to:`/entity/${$.sha}`,className:"flex items-center gap-4 flex-1 min-w-0 no-underline",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(dt,{size:16,style:{color:"#8B5CF6"}})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"font-semibold text-gray-900 text-sm mb-1",children:$.name}),n("div",{className:"text-xs text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:$.filePath})]})]}),n("button",{onClick:()=>J($.sha,$.filePath||""),disabled:m.state!=="idle"||g!==null,className:"px-4 py-2 text-white border-none rounded text-sm font-medium cursor-pointer transition-all whitespace-nowrap shrink-0 disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:U=>U.currentTarget.style.backgroundColor="#004560",onMouseLeave:U=>U.currentTarget.style.backgroundColor="#005C75",title:g?"Please wait for current analysis to complete":"Analyze this entity",children:"Analyze"})]})},$.sha))})}):n("p",{className:"text-base text-gray-600 m-0 mb-6 leading-relaxed mt-6",children:"Run analysis on your visual components to create simulations and capture screenshots"})]})]})]}),b&&i&&n(rt,{projectSlug:i,onClose:()=>w(!1)})]})})}),iu=Object.freeze(Object.defineProperty({__proto__:null,default:ou,loader:su,meta:au},Symbol.toStringTag,{value:"Module"}));function lu({entity:e,currentRun:t,queueState:r}){const a=fe(),s=e.entityType==="visual"||e.entityType==="library",o=e.analyses?.[0],i=o?.status,l=o?.scenarios||[],d=o?.entitySha!==e.sha,m=i?.scenarios||[],u=m.filter(S=>S.screenshotFinishedAt).length,h=!d&&l.length>0&&u===l.length,f=l.length>0&&!h&&!d,g=r?.jobs.some(S=>S.entityShas?.includes(e.sha)||S.type==="analysis"&&S.entityShas&&S.entityShas.length===0)??!1,b=(t?.currentEntityShas?.includes(e.sha)??!1)||(r?.currentlyExecuting?.entityShas?.includes(e.sha)??!1)||f,w=V(()=>{a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})},[e,a]),x=zn(e),C=e.metadata?.isSuperseded===!0,v=b||g;return c("div",{className:`flex flex-col gap-1.5 p-3 rounded-lg transition-all ${e.metadata?.isUncommitted?"border-l-4 border-l-amber-500 bg-amber-50":"bg-white hover:bg-gray-100"}`,children:[c("div",{className:"flex justify-between items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 overflow-hidden",children:[n(Fe,{type:e.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n(Z,{to:`/entity/${e.sha}`,className:"font-semibold text-sm text-gray-900 whitespace-nowrap",children:e.name}),n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-medium",style:e.entityType==="visual"?{backgroundColor:"#7c3aed0D",color:"#7c3aed"}:e.entityType==="library"?{backgroundColor:"#0DBFE90D",color:"#0DBFE9"}:e.entityType==="type"?{backgroundColor:"#dc26260D",color:"#dc2626"}:e.entityType==="data"?{backgroundColor:"#2563eb0D",color:"#2563eb"}:e.entityType==="index"?{backgroundColor:"#ea580c0D",color:"#ea580c"}:e.entityType==="functionCall"?{backgroundColor:"#7c3aed0D",color:"#7c3aed"}:e.entityType==="class"?{backgroundColor:"#0596690D",color:"#059669"}:e.entityType==="method"?{backgroundColor:"#0891b20D",color:"#0891b2"}:{backgroundColor:"#6b72800D",color:"#6b7280"},children:e.entityType})]}),n("div",{className:"text-xs text-gray-500 mt-0.5 truncate",children:e.filePath}),e.description&&n("div",{className:"text-sm text-gray-600 mt-1 italic",children:e.description})]})]}),n("div",{className:"flex-1 shrink flex justify-end items-center gap-3",children:c("div",{className:"flex items-center gap-3",children:[b?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Be,{size:14,className:"animate-spin"}),"Analyzing..."]}):e.analyses&&e.analyses.length>0?c("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-lg bg-green-50",children:[n("div",{className:"w-2 h-2 rounded-full bg-green-500"}),n("span",{className:"text-xs text-green-700",children:"Up to date"})]}):c("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-lg bg-gray-100",children:[n("div",{className:"w-2 h-2 rounded-full border border-gray-400"}),n("span",{className:"text-xs text-gray-700",children:"Not yet analyzed"})]}),s&&!b&&n("button",{onClick:w,disabled:v,className:`px-3 py-1.5 border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap ${g?"bg-purple-50 border border-purple-300 text-purple-700":b?"bg-pink-50 border border-pink-300 cursor-not-allowed":"bg-white text-white hover:-translate-y-px"}`,style:!g&&!b?{backgroundColor:"#005C75"}:{},onMouseEnter:S=>{!g&&!b&&(S.currentTarget.style.backgroundColor="#004560")},onMouseLeave:S=>{!g&&!b&&(S.currentTarget.style.backgroundColor="#005C75")},title:b?"Analysis in progress":g?"Already queued for analysis":"Analyze this entity",children:g?c("span",{className:"flex items-center gap-1.5",children:[n(kt,{size:16,color:e.entityType==="visual"?"#7c3aed":"#14b8a6"}),n("span",{children:"Queued"})]}):b?c("span",{className:"flex items-center gap-1.5 text-pink-600",children:[n(Be,{size:16,className:"animate-spin",color:"#ec4899"}),n("span",{children:"Analyzing..."})]}):"Analyze"})]})})]}),l.length>0&&n("div",{className:"flex gap-2 flex-wrap px-0 mt-3",children:l.slice(0,5).map((S,N)=>{if(!S.id)return null;if(e.entityType==="library")return n(On,{scenario:S,entitySha:e.sha,size:"medium",isOutdated:C||x},N);const E=S.metadata?.screenshotPaths?.[0],A=Ln(S,i,!!b,e.sha,r),I=m.find(T=>T.name===S.name);if(f&&I?.startedAt&&I?.screenshotStartedAt,A.isCaptured)return n(Z,{to:`/entity/${e.sha}/scenarios/${S.id}`,className:`relative w-20 h-15 border-2 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md ${C||x?"border-amber-500 hover:border-amber-600":"border-gray-200 hover:border-blue-600"}`,children:n(be,{screenshotPath:E,alt:S.name,title:S.name,className:"max-w-full max-h-full object-contain object-center"})},N);{const T=A.hasError?"text-red-500":"text-gray-400";return n(Z,{to:`/entity/${e.sha}/scenarios/${S.id}`,className:`w-20 h-15 border-2 border-dashed ${A.borderColor} rounded ${A.bgColor} flex items-center justify-center text-2xl`,title:A.title,children:n("span",{className:A.shouldSpin?"animate-pulse":T,children:A.icon})},N)}})})]})}function cu({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i}){const[l,d]=bn(),[m,u]=k(new Set),[h,p]=k(""),[f,g]=k(!1),[y,b]=k("all"),w=o||"all",x=(_,R=[])=>{if(R.some(q=>q.entityShas?.includes(_.sha)))return"analyzing";if(!_.analyses||_.analyses.length===0)return"not-analyzed";const Y=_.analyses[0],J=Y.createdAt?new Date(Y.createdAt).getTime():0,F=_.metadata?.editedAt?new Date(_.metadata.editedAt).getTime():0;return J>=F?"up-to-date":"out-of-date"},C=ee(()=>{let _=e;return w!=="all"&&(_=_.filter(R=>R.entityType===w)),s==="analyzed"&&(_=_.filter(R=>R.analyses&&R.analyses.length>0)),_},[e,w,s]),v=ee(()=>{const _=new Map,R=new Map,O=new Map;C.forEach(F=>{const q=`${F.filePath}::${F.name}`,K=R.get(q);if(!K)R.set(q,F),O.set(q,[]);else{const $=K.metadata?.editedAt||K.createdAt||"",U=F.metadata?.editedAt||F.createdAt||"";let j=!1;if(U>$)j=!0;else if(U===$){const B=K.createdAt||"";j=(F.createdAt||"")>B}j?(O.get(q).push(K),R.set(q,F)):O.get(q).push(F)}}),R.forEach((F,q)=>{if(!(F.analyses&&F.analyses.length>0)&&F.metadata?.previousVersionWithAnalyses){const U=(O.get(q)||[]).find(j=>j.sha===F.metadata?.previousVersionWithAnalyses);U&&U.analyses&&U.analyses.length>0&&(F.analyses=U.analyses)}}),Array.from(R.values()).sort((F,q)=>{const K=!F.metadata?.notExported&&!F.metadata?.namedExport,$=!q.metadata?.notExported&&!q.metadata?.namedExport;return K&&!$?-1:!K&&$?1:0}).forEach(F=>{const q=F.filePath??"No File Path";_.has(q)||_.set(q,{filePath:q,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const K=_.get(q);K.entities.push(F),K.totalCount++,F.metadata?.isUncommitted&&K.uncommittedCount++;const $=F.analyses?.[0]?.scenarios?.length||0;K.simulationCount+=$;const U=F.metadata?.editedAt||F.updatedAt;U&&(!K.lastUpdated||new Date(U)>new Date(K.lastUpdated))&&(K.lastUpdated=U)});const Y=i?.jobs||[];_.forEach(F=>{const q=F.entities.map(K=>x(K,Y));q.includes("analyzing")?F.state="analyzing":q.includes("out-of-date")?F.state="out-of-date":q.includes("not-analyzed")?F.state="not-analyzed":F.state="up-to-date"}),_.forEach(F=>{for(const q of F.entities){if(F.previewScreenshots.length+F.previewLibraryScenarios.length>=3)break;const $=q.analyses?.[0]?.scenarios||[];if(q.entityType==="library"){const U=$.find(j=>j.metadata?.executionResult||j.metadata?.error);U&&F.previewLibraryScenarios.push({scenario:U,entitySha:q.sha})}else{const U=$.find(j=>j.metadata?.screenshotPaths?.[0]);if(U){const j=U.metadata?.screenshotPaths?.[0],B=!!U.metadata?.error;j&&!F.previewScreenshots.includes(j)&&(F.previewScreenshots.push(j),F.previewScreenshotErrors.push(B))}}}});const J=Array.from(_.values());return J.sort((F,q)=>{if(s==="analyzed"){const U=Math.max(...F.entities.filter(B=>B.analyses?.[0]?.createdAt).map(B=>new Date(B.analyses[0].createdAt).getTime()),0);return Math.max(...q.entities.filter(B=>B.analyses?.[0]?.createdAt).map(B=>new Date(B.analyses[0].createdAt).getTime()),0)-U}if(F.uncommittedCount>0&&q.uncommittedCount===0)return-1;if(F.uncommittedCount===0&&q.uncommittedCount>0)return 1;const K=F.lastUpdated?new Date(F.lastUpdated).getTime():0;return(q.lastUpdated?new Date(q.lastUpdated).getTime():0)-K}),J},[C,s]),S=ee(()=>{let _=v;if(y!=="all"&&(_=_.filter(R=>R.state===y)),h.trim()){const R=h.toLowerCase();_=_.filter(O=>O.filePath.toLowerCase().includes(R))}return _},[v,h,y]),N=(t-1)*r,E=N+r,A=S.slice(N,E),I=Math.ceil(S.length/r),T=_=>{u(R=>{const O=new Set(R);return O.has(_)?O.delete(_):O.add(_),O})},M=()=>{if(f)u(new Set),g(!1);else{const _=new Set(A.map(R=>R.filePath));u(_),g(!0)}},P=_=>{switch(_){case"analyzing":return{text:"Analyzing...",bgColor:"bg-pink-100",textColor:"text-pink-700",borderColor:"border-pink-300"};case"up-to-date":return{text:"Up to date",bgColor:"bg-green-100",textColor:"text-green-700",borderColor:"border-green-300"};case"out-of-date":return{text:"Out of date",bgColor:"bg-yellow-100",textColor:"text-yellow-700",borderColor:"border-yellow-300"};case"not-analyzed":return{text:"Not analyzed",bgColor:"bg-gray-100",textColor:"text-gray-600",borderColor:"border-gray-300"}}},L=_=>_?new Date(_).toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0}):"Never";return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[10px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{value:w,onChange:_=>{const R=_.target.value,O=new URLSearchParams(l);R==="all"?O.delete("entityType"):O.set("entityType",R),O.set("page","1"),d(O)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 py-2 pr-8 text-sm 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(hn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative",children:[c("select",{value:y,onChange:_=>b(_.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 py-2 pr-8 text-sm 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:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(hn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Er,{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:h,onChange:_=>p(_.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]}),n("button",{onClick:M,className:"px-3 py-2 border-none rounded text-sm font-medium cursor-pointer transition-colors whitespace-nowrap bg-[#005c75] text-white hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:f?"Collapse All":"Expand All"})]})]}),n("div",{className:"flex flex-col gap-3",children:A.map(_=>{const R=m.has(_.filePath),O=_.uncommittedCount>0;return c("div",{className:"bg-white overflow-hidden",style:R?{border:"1px solid #e5e7eb",borderLeft:"4px solid #306AFF",borderRadius:"8px"}:{borderRadius:"8px"},children:[c("div",{className:"flex justify-between items-center p-3 cursor-pointer select-none transition-colors hover:bg-gray-200",style:{outlineColor:"#005C75"},onClick:()=>T(_.filePath),role:"button",tabIndex:0,onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),T(_.filePath))},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"text-gray-500 text-xs w-4 inline-block shrink-0",children:R?"▼":"▶"}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n("span",{className:"font-normal text-gray-900 text-sm overflow-hidden text-ellipsis whitespace-nowrap",children:_.filePath}),O&&c("span",{className:"text-[12px] text-amber-500 font-medium shrink-0 whitespace-nowrap",children:[_.uncommittedCount," uncommitted"]})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[(_.previewScreenshots.length>0||_.previewLibraryScenarios.length>0)&&c("div",{className:"flex gap-1.5 items-center h-[38px]",children:[_.previewScreenshots.map((Y,J)=>{const F=_.previewScreenshotErrors[J];return c("div",{className:`relative w-[50px] h-[38px] border ${F?"border-red-400":"border-gray-200"} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center`,children:[n(be,{screenshotPath:Y,alt:`Preview ${J+1}`,className:"max-w-full max-h-full object-contain object-center"}),F&&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(Ya,{size:12,color:"white"})})]},`screenshot-${J}`)}),_.previewLibraryScenarios.map((Y,J)=>n(On,{scenario:Y.scenario,entitySha:Y.entitySha,size:"small",showBorder:!0},`library-${J}`))]}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-[13px] text-gray-500",children:_.simulationCount===0?"-":`${_.simulationCount} simulations`}),c("span",{className:"text-[13px] text-gray-500",children:[_.totalCount," ",_.totalCount===1?"entity":"entities"]}),(()=>{const Y=P(_.state);return n("span",{className:`text-[12px] px-2 py-1 rounded ${Y.bgColor} ${Y.textColor}`,children:Y.text})})(),n("span",{className:"text-[11px] text-gray-400",children:L(_.lastUpdated)})]})]})]}),R&&n("div",{className:"p-2 bg-gray-50 flex flex-col gap-2",children:_.entities.map(Y=>n(lu,{entity:Y,currentRun:a,queueState:i},Y.sha))})]},_.filePath)})}),I>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(l),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",I]}),t<I&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(l),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const du=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function uu({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,l=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([wt(),Ke()]);return D({entities:d,currentCommit:m,page:a,filter:s,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),D({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const mu=_e(function(){const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i}=Ie(),l=nt(),d=ee(()=>{if(!t)return[];const h=new Set([]);for(const p of t)h.add(p.filePath??"No File Path");return Array.from(h)},[t]),m=ee(()=>t?t.sort((h,p)=>h.metadata?.isUncommitted&&!p.metadata?.isUncommitted?-1:!h.metadata?.isUncommitted&&p.metadata?.isUncommitted?1:new Date(p.metadata?.editedAt||0).getTime()-new Date(h.metadata?.editedAt||0).getTime()):[],[t]),u=ee(()=>{if(!t)return[];const h=new Set([]);for(const p of t)p.metadata?.isUncommitted&&h.add(p.filePath??"No File Path");return Array.from(h)},[t]);return t?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Files & Entities"}),c("div",{className:"flex gap-4 text-sm text-gray-500 mt-2",children:[l.state==="loading"&&n("span",{className:"text-blue-600 font-medium animate-pulse",children:"🔄"}),c("span",{children:[d.length," files"]}),c("span",{children:[t.length," entities"]}),c("span",{className:"text-amber-500 font-medium",children:[u.length," uncommitted files"]})]})]}),n(cu,{entities:m,page:a,itemsPerPage:50,currentRun:r?.metadata?.currentRun,filter:s,entityType:o,queueState:i})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:"Unable to retrieve entities"})]})})}),hu=Object.freeze(Object.defineProperty({__proto__:null,default:mu,loader:uu,meta:du},Symbol.toStringTag,{value:"Module"}));function pu(e,t,r){const[a,s]=k(()=>new Set(t)),[o,i]=k(()=>new Set(r)),l=pe([]),d=pe([]);return G(()=>{(t.length!==l.current.length||t.some((y,b)=>y!==l.current[b]))&&(l.current=t,s(y=>{const b=new Set(y);return t.forEach(w=>{y.has(w)||b.add(w)}),b}))},[t]),G(()=>{(r.length!==d.current.length||r.some((y,b)=>y!==d.current[b]))&&(d.current=r,i(y=>{const b=new Set(y);return r.forEach(w=>{y.has(w)||b.add(w)}),b}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,b)=>{b(w=>{const x=new Set(w);return x.has(g)?x.delete(g):x.add(g),x})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function fu(e,t,r){const[a,s]=k(null),[o,i]=k(null),l=fe();G(()=>{l.data?.oldContent!==void 0&&l.data?.newContent!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=h=>{s({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType",r==="branch"?"branch":"uncommitted"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},m=(h,p)=>{s({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType",r==="branch"?"branch":"uncommitted"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function gu(e){const t=fe(),{showToast:r}=_n();G(()=>{if(t.state==="idle"&&t.data){const i=t.data;i?.error&&r(`Error: ${i.error}`,"error",6e3)}},[t.state,t.data,r]);const a=i=>{console.log("Generate analysis clicked for entity:",i.sha,i.name);const l=new FormData;l.append("entitySha",i.sha),l.append("filePath",i.filePath||""),t.submit(l,{method:"post",action:"/api/analyze"})},s=i=>{const l=i.filter(u=>u.entityType==="visual"||u.entityType==="library");console.log("Generate analysis for all entities:",l.length);const d=l.map(u=>u.sha).join(","),m=new FormData;m.append("entityShas",d),t.submit(m,{method:"post",action:"/api/analyze"})},o=i=>e?.includes(i)??!1;return{isAnalyzing:t.state!=="idle",handleGenerateSimulation:a,handleGenerateAllSimulations:s,isEntityBeingAnalyzed:o}}function yu({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){const[o,i]=k(!1),[l,d]=k(!1);return G(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",a.find(m=>m.sha===e.entitySha)?.name||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors",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",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(gs,{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",children:"Close"})})]})})}function xu({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200 mb-6",children:c("nav",{className:"flex gap-8 items-center",children:[n("button",{onClick:()=>t("uncommitted"),className:`relative pb-4 px-2 text-sm font-medium transition-colors ${e==="uncommitted"?"text-[#005C75] border-b-2 border-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#e8f1f5] text-[#005C75]":"bg-gray-200 text-gray-700"}`,children:r})]})}),n("button",{onClick:()=>t("branch"),className:`relative pb-4 px-2 text-sm font-medium transition-colors ${e==="branch"?"text-[#005C75] border-b-2 border-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:c("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-[#e8f1f5] text-[#005C75]":"bg-gray-200 text-gray-700"}`,children:a})]})})]})})}function bu(e,t){const a=t.match(/text-(\w+)-\d+/)?.[1]||"gray",o={green:"#15803d",gray:"#374151",orange:"#b45309",blue:"#1e40af",amber:"#b45309",purple:"#6b21a8"}[a]||"#374151";switch(e){case"✓":return n($t,{size:16,color:o});case"○":return n(Ba,{size:16,color:o});case"⚠":return n(vn,{size:16,color:o});case"●":return n(_r,{size:16,color:o});case"+":return n(za,{size:16,color:o});default:return e}}function wu({entity:e,variant:t="full"}){const r=Yn(e),{badge:a}=r,s=bu(a.icon,a.color);return t==="icon-only"?n("span",{className:`${a.color} text-sm font-bold`,title:a.label,children:s}):t==="compact"?n("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-normal border ${a.color} ${a.bgColor} ${a.borderColor}`,title:a.label,children:n("span",{children:a.label})}):n("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-normal border ${a.color} ${a.bgColor} ${a.borderColor}`,children:n("span",{children:a.label})})}function vu({entity:e,filePath:t,impactedEntities:r,isBeingAnalyzed:a,isQueued:s,projectSlug:o,diffType:i,baseBranch:l,currentBranch:d,onGenerateSimulation:m,onShowLogs:u}){const h=e.analyses?.[0],p=h?.scenarios||[],f=h?.status?.scenarios||[];return c("div",{className:"flex flex-col gap-2 p-3 bg-white border border-[#e1e1e1] rounded-md transition-all hover:border-[#005c75] hover:shadow-sm",children:[c("div",{className:"flex items-center gap-2",children:[c(Z,{to:`/entity/${e.sha}`,className:"flex items-center gap-3 flex-1 min-w-0 no-underline",children:[n(Fe,{type:e.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"font-['IBM_Plex_Sans'] font-medium text-sm text-[#343434] flex items-center gap-2",children:[n("span",{children:e.name}),e.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),e.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),e.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"}),n(wu,{entity:e,variant:"full"})]}),e.description&&n("div",{className:"font-['IBM_Plex_Sans'] text-xs text-[#8e8e8e] mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap",children:e.description})]}),c("div",{className:"flex items-center gap-2",children:[a&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[c("svg",{className:"animate-spin h-3.5 w-3.5",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"})]}),"Analyzing..."]}),!a&&s&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"})]})]}),(e.entityType==="visual"||e.entityType==="library")&&!a&&!s&&n("button",{onClick:g=>{g.stopPropagation(),m(e)},className:"px-3 py-1.5 bg-[#005c75] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors whitespace-nowrap",title:"Analyze this entity",children:"Analyze"}),a&&o&&n("button",{onClick:g=>{g.stopPropagation(),u(e.sha)},className:"px-3 py-1.5 bg-[#626262] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-semibold hover:bg-[#4a4a4a] transition-colors whitespace-nowrap",title:"View analysis logs",children:"📋 Logs"})]}),(e.entityType==="visual"||e.entityType==="library")&&p.length>0&&n("div",{className:"flex gap-2.5 mt-3 overflow-x-auto pb-1",children:p.map((g,y)=>{const b=g.metadata?.screenshotPaths?.[0],w=f.find(v=>v.name===g.name),x=w?.screenshotStartedAt&&!w?.screenshotFinishedAt,C=!!b;return n(Z,{to:g.id?`/entity/${e.sha}/scenarios/${g.id}`:`/entity/${e.sha}`,className:"shrink-0 block no-underline",children:n("div",{className:"w-36 h-24 rounded-md border border-gray-200 overflow-hidden bg-gray-100 flex items-center justify-center transition-all",onMouseEnter:v=>{v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)"},onMouseLeave:v=>{v.currentTarget.style.borderColor="#d1d5db",v.currentTarget.style.boxShadow="none"},children:C?n(be,{screenshotPath:b,alt:g.name,className:"max-w-full max-h-full object-contain"}):n("span",{className:`text-2xl ${x?"animate-pulse":"text-gray-400"}`,children:x?"⋯":"⏹️"})})},y)})})]})}function Cu({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:l,onToggleFile:d,onShowFileDiff:m,onGenerateSimulation:u,onShowLogs:h}){return n("div",{children:e.length>0?n("div",{className:"flex flex-col gap-3",children:e.map(([p,{status:f,editedEntities:g}])=>{const y=r.has(p);return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>d(p),role:"button",tabIndex:0,onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d(p))},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:y?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:p}),c("span",{className:"text-xs text-gray-500",children:[g.length," entit",g.length!==1?"ies":"y"]})]})]})}),y&&g.length>0&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:g.map(b=>n(vu,{entity:b,filePath:p,impactedEntities:t.get(b.sha)||[],isBeingAnalyzed:a(b.sha),isQueued:s(b.sha),projectSlug:o,diffType:"uncommitted",baseBranch:i,currentBranch:l,onGenerateSimulation:u,onShowLogs:h},b.sha))})]},p)})}):c("div",{className:"py-12 px-6 text-center",children:[n("div",{className:"text-6xl mb-4 opacity-50",children:"✓"}),n("p",{className:"font-['IBM_Plex_Sans'] text-lg font-semibold text-[#3e3e3e] mb-2",children:"No edited entities"}),c("p",{className:"font-['IBM_Plex_Sans'] text-sm text-[#8e8e8e]",children:["There are no uncommitted changes.",n("br",{}),n("br",{}),"If you edit a file in the project, it will show up here."]})]})})}function Nu({status:e}){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"}}[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${r.bgColor}`,title:e,children:r.label}),r.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 Su({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,isAnyAnalysisInProgress:d,isAnalyzing:m,lastLogLine:u,projectSlug:h,onToggleFile:p,onBranchChange:f,onGenerateSimulation:g,onShowLogs:y}){return e.length>0&&e.some(([b,{entities:w}])=>w.length>0),c("div",{children:[n("div",{className:"mb-5",children:t===r?c("p",{className:"text-sm text-gray-500",children:["Currently on the primary branch"," ",n("strong",{className:"text-gray-900 font-semibold",children:t})]}):c("p",{className:"text-sm text-gray-500",children:["Changes in"," ",n("strong",{className:"text-gray-900 font-semibold",children:t})," ","compared to"," ",n("select",{value:a,onChange:b=>f(b.target.value),className:"py-0.5 px-2 bg-white border border-gray-300 rounded-md text-sm font-semibold text-gray-900 cursor-pointer hover:border-indigo-500",children:s.filter(b=>b!==t).map(b=>n("option",{value:b,children:b},b))})]})}),t===r?c("div",{className:"py-12 px-6 text-center bg-blue-50 rounded-lg border border-blue-100",children:[n("div",{className:"text-6xl mb-4",children:"ℹ️"}),n("p",{className:"text-lg font-semibold text-gray-900 mb-3",children:"You're on the primary branch"}),c("p",{className:"text-sm text-gray-600 mb-2 max-w-md mx-auto",children:["When you switch to a feature branch, this section will show all the changes between your branch and"," ",n("strong",{className:"font-semibold",children:r}),"."]}),n("p",{className:"text-sm text-gray-600 max-w-md mx-auto",children:"This helps you understand what will be included in your pull request before you create it."})]}):e.length>0?n("div",{className:"flex flex-col gap-3",children:e.map(([b,{status:w,entities:x}])=>{const C=o.has(b);return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>p(b),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p(b))},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:C?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:b}),n(Nu,{status:w.status})]}),c("span",{className:"text-xs text-gray-500",children:[x.length," entit",x.length!==1?"ies":"y"]})]})]})}),C&&x.length>0&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-2 flex flex-col gap-1.5",children:x.map(v=>{const S=i(v.sha),N=l(v.sha),E=S&&u,A=v.analyses?.[0],I=A?.scenarios||[],T=A?.status?.scenarios||[];return c("div",{className:"flex flex-col gap-2 p-3 bg-white border border-gray-200 rounded-md transition-all hover:border-blue-600 hover:shadow-sm",children:[c("div",{className:"flex items-center gap-2",children:[c(Z,{to:`/entity/${v.sha}`,className:"flex items-center gap-3 flex-1 min-w-0 no-underline",children:[n(Fe,{type:v.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"font-['IBM_Plex_Sans'] font-medium text-sm text-[#343434] flex items-center gap-2",children:[n("span",{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:"font-['IBM_Plex_Sans'] text-xs text-[#8e8e8e] mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap",children:v.description})]}),c("div",{className:"flex items-center gap-2",children:[S&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[c("svg",{className:"animate-spin h-3.5 w-3.5",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"})]}),"Analyzing..."]}),!S&&N&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"})]})]}),(v.entityType==="visual"||v.entityType==="library")&&n("button",{onClick:M=>{M.stopPropagation(),g(v)},disabled:m||d||N||S,className:"px-3 py-1.5 bg-[#005c75] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors whitespace-nowrap disabled:bg-gray-400 disabled:cursor-not-allowed",title:N?"Entity is queued for analysis":S?"Entity is being analyzed":d?"Please wait for current analysis to complete":"Analyze this entity",children:S?"Analyzing...":N?"Queued":d?"Waiting...":"Analyze"}),S&&h&&n("button",{onClick:M=>{M.stopPropagation(),y(v.sha)},className:"px-3 py-1.5 bg-[#626262] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#4a4a4a] transition-colors whitespace-nowrap",title:"View analysis logs",children:"📋 Logs"})]}),E&&c("div",{className:"flex items-center gap-1.5 text-[13px] font-medium text-blue-600 px-2 py-1 bg-blue-50 rounded",children:[n("span",{className:"animate-spin",children:"⚙️"}),n("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-xs max-w-full",title:u,children:u})]}),I.length>0&&n("div",{className:"flex gap-2 flex-wrap",children:I.slice(0,5).map((M,P)=>{const L=M.metadata?.screenshotPaths?.[0],_=T.find(J=>J.name===M.name),R=_?.screenshotStartedAt&&!_?.screenshotFinishedAt,O=!!L,Y=zn(v)||v.metadata?.isSuperseded;return O?n(Z,{to:`/entity/${v.sha}/scenarios/${M.id}`,className:`relative w-20 h-15 border-2 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md ${Y?"border-amber-500 hover:border-amber-600":"border-gray-200 hover:border-blue-600"}`,children:n(be,{screenshotPath:L,alt:M.name,title:M.name,className:"max-w-full max-h-full object-contain object-center"})},P):n(Z,{to:`/entity/${v.sha}/scenarios/${M.id}`,className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`Capturing ${M.name}...`,children:n("span",{className:R?"animate-spin":"text-gray-400",children:R?"⏳":"⏹️"})},P)})})]},v.sha)})})]},b)})}):c("div",{className:"py-12 px-6 text-center",children:[n("div",{className:"text-6xl mb-4 opacity-50",children:"✓"}),n("p",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No differences found"}),c("p",{className:"text-sm text-gray-500",children:["This branch is up to date with ",a]})]})]})}const Au=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Eu({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"),l=t.get("entitySha");let d;return s==="branch"?d=It(a,o,i):d=bl(a),D({...d,entitySha:l})}return D({error:"Unknown action"},{status:400})}async function _u({request:e,context:t}){try{const a=new URL(e.url).searchParams.get("compare"),s=t.analysisQueue,o=s?s.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([wt(),Ke(),Pe()]),m=ra(),u=pl(),h=fl(),p=gl(),f=a||h;let g=[];return u&&u!==f&&(g=aa(f,u)),D({entities:i||[],gitStatus:m,currentBranch:u,defaultBranch:h,allBranches:p,baseBranch:f,branchDiff:g,currentCommit:l,projectSlug:d,queueState:o})}catch(r){return console.error("Failed to load git data:",r),D({entities:[],gitStatus:[],currentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const Pu=_e(function(){const{entities:t,gitStatus:r,currentBranch:a,defaultBranch:s,allBranches:o,baseBranch:i,branchDiff:l,currentCommit:d,projectSlug:m,queueState:u}=Ie(),[h,p]=bn(),[f,g]=k("uncommitted"),[y,b]=k(null),w=h.get("expanded")==="true",x=fe(),C=x.data;G(()=>{f==="branch"&&a&&i&&a!==i&&x.state==="idle"&&!C&&x.load(`/api/branch-entity-diff?base=${encodeURIComponent(i)}&compare=${encodeURIComponent(a)}`)},[f,a,i,x,C]);const v=ee(()=>{const X=ha(r,t);return Array.from(X.entries()).sort((Te,Ne)=>Te[0].localeCompare(Ne[0]))},[r,t]),S=ee(()=>{const X=tu(l,t,C);return Array.from(X.entries()).sort((Te,Ne)=>Te[0].localeCompare(Ne[0]))},[l,t,C]),N=ee(()=>nu(r,t),[r,t]);ee(()=>{const X=S.flatMap(([Te,Ne])=>Ne.entities);return ru(X,t)},[S,t]);const E=ee(()=>v.map(([X])=>X),[v]),A=ee(()=>S.map(([X])=>X),[S]),{expandedUncommitted:I,expandedBranch:T,setExpandedUncommitted:M,setExpandedBranch:P,toggleFile:L,expandAllUncommitted:_,collapseAllUncommitted:R,expandAllBranch:O,collapseAllBranch:Y}=pu(w,E,A),{diffView:J,diffContent:F,isLoading:q,handleShowFileDiff:K,handleCloseDiff:$}=fu(i,a,f),U=d?.metadata?.currentRun,j=!!U?.createdAt&&!U?.analysisCompletedAt,{lastLine:B,isCompleted:te}=Ye(m,j),ue=j&&!te,W=new Set(U?.currentEntityShas||[]),ne=new Set(u.jobs.flatMap(X=>X.entityShas||[])),Me=new Set(u.currentlyExecuting?.entityShas||[]),{isAnalyzing:ye,handleGenerateSimulation:it,handleGenerateAllSimulations:lt,isEntityBeingAnalyzed:ct}=gu(U?.currentEntityShas),Ve=X=>ne.has(X)||Me.has(X),vt=X=>{X===s?h.delete("compare"):h.set("compare",X),p(h)},Xt=()=>{const Te=(f==="uncommitted"?v.flatMap(([Ne,nn])=>nn.editedEntities):S.flatMap(([Ne,nn])=>nn.entities)).filter(Ne=>!W.has(Ne.sha)&&!ne.has(Ne.sha)&&!Me.has(Ne.sha));lt(Te)},Ct=v.length,Nt=S.length,en=f==="uncommitted"?Ct:Nt,me=(f==="uncommitted"?v.flatMap(([X,Te])=>Te.editedEntities):S.flatMap(([X,Te])=>Te.entities)).filter(X=>X.entityType==="visual"||X.entityType==="library"),de=me.length>0&&me.every(X=>W.has(X.sha)),xe=me.length>0&&!de&&me.every(X=>ne.has(X.sha)||Me.has(X.sha)),tn=ye||de||xe,Le=de?"Analyzing...":xe?"Queued...":ye?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Git Changes"}),n("div",{className:"flex items-center gap-4 text-sm text-gray-600 mt-2",children:a&&c(re,{children:[n("span",{className:"text-xs",children:"Branch:"}),o.length>0?n("select",{value:a,onChange:X=>vt(X.target.value),className:"text-gray-900 font-medium px-2 py-1 border border-gray-300 rounded text-sm hover:border-gray-400 focus:outline-none focus:border-blue-500",style:{paddingRight:"26px",backgroundPosition:"right 6px center",backgroundRepeat:"no-repeat",backgroundSize:"16px",appearance:"none",backgroundImage:`url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e")`},children:o.map(X=>c("option",{value:X,children:[X," ",X===s?"(default)":""]},X))}):n("span",{className:"text-gray-900 font-medium",children:a})]})})]}),c("div",{className:"flex items-center justify-between mb-1",children:[n(xu,{activeTab:f,onTabChange:g,uncommittedCount:Ct,branchCount:Nt}),en>0&&c("div",{className:"flex gap-2",children:[n("button",{onClick:f==="uncommitted"?_:O,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#626262] hover:text-cyblack-100 hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Expand All"}),n("button",{onClick:f==="uncommitted"?R:Y,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#626262] hover:text-cyblack-100 hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Collapse All"}),n("button",{onClick:Xt,disabled:tn,className:"px-4 py-1.5 bg-[#005c75] text-white rounded text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed",title:tn?Le:`Analyze all ${f} entities`,children:Le})]})]}),c("div",{className:"overflow-hidden",children:[f==="uncommitted"&&n(Cu,{files:v,entityImpactMap:N,expandedFiles:I,isEntityBeingAnalyzed:ct,isEntityQueued:Ve,projectSlug:m,baseBranch:i,currentBranch:a,onToggleFile:X=>L(X,I,M),onShowFileDiff:K,onGenerateSimulation:it,onShowLogs:b}),f==="branch"&&a&&n(Su,{files:S,currentBranch:a,defaultBranch:s,baseBranch:i,allBranches:o,expandedFiles:T,isEntityBeingAnalyzed:ct,isEntityQueued:Ve,isAnyAnalysisInProgress:ue,isAnalyzing:ye,lastLogLine:B,projectSlug:m,onToggleFile:X=>L(X,T,P),onBranchChange:vt,onGenerateSimulation:it,onShowLogs:b})]}),J&&n(yu,{diffView:J,diffContent:F,isLoading:q,entities:t,onClose:$}),y&&m&&n(rt,{projectSlug:m,onClose:()=>b(null)})]})})}),Mu=Object.freeze(Object.defineProperty({__proto__:null,action:Eu,default:Pu,loader:_u,meta:Au},Symbol.toStringTag,{value:"Module"})),ym={entry:{module:"/assets/entry.client-B5l8I1m3.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/index-BgDzgbQW.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-o8NMI2bW.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/index-BgDzgbQW.js","/assets/file-text-fb2mx25c.js","/assets/settings-C7G4GDvW.js","/assets/useToast-XY00p4rI.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/LogViewer-CRcT5fOZ.js","/assets/clock-DXui5oLF.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-69R47Ffu.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/InteractivePreview-CRfBaL5B.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/index-BgDzgbQW.js"],css:["/assets/InteractivePreview-CMKNK2uU.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-BRD2FrH5.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/InteractivePreview-CRfBaL5B.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/index-BgDzgbQW.js"],css:["/assets/InteractivePreview-CMKNK2uU.css"],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-Dv3k2aEm.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/settings-C7G4GDvW.js","/assets/file-text-fb2mx25c.js","/assets/LogViewer-CRcT5fOZ.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/ScenarioPreview-Dj4Mm0AR.js","/assets/chart-column-DOftqM9U.js","/assets/circle-alert-0WShkwuc.js","/assets/SafeScreenshot-Bual6h18.js","/assets/LibraryFunctionPreview-BYVx9KFp.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-BxaXKsIx.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/InteractivePreview-CRfBaL5B.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/ScenarioPreview-Dj4Mm0AR.js","/assets/ScenarioViewer-wtCIkGzq.js","/assets/SafeScreenshot-Bual6h18.js","/assets/EntityTypeIcon-BFRmw1TF.js","/assets/LogViewer-CRcT5fOZ.js","/assets/loader-circle-DE3HAwpF.js","/assets/index-BgDzgbQW.js","/assets/LibraryFunctionPreview-BYVx9KFp.js","/assets/file-text-fb2mx25c.js","/assets/circle-alert-0WShkwuc.js","/assets/chart-column-DOftqM9U.js"],css:["/assets/InteractivePreview-CMKNK2uU.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-Duh3oShE.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/SafeScreenshot-Bual6h18.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/EntityTypeIcon-BFRmw1TF.js","/assets/search-BymWwY_X.js","/assets/file-text-fb2mx25c.js","/assets/chart-column-DOftqM9U.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.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!1,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-DPFKgE96.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/ScenarioViewer-wtCIkGzq.js","/assets/InteractivePreview-CRfBaL5B.js","/assets/LogViewer-CRcT5fOZ.js","/assets/SafeScreenshot-Bual6h18.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/index-BgDzgbQW.js"],css:["/assets/InteractivePreview-CMKNK2uU.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-Dc4MlMpK.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.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-Cjdlwanz.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/useToast-XY00p4rI.js","/assets/LogViewer-CRcT5fOZ.js","/assets/EntityTypeIcon-BFRmw1TF.js","/assets/SafeScreenshot-Bual6h18.js","/assets/file-text-fb2mx25c.js","/assets/settings-C7G4GDvW.js","/assets/zap-Dra7vum1.js","/assets/loader-circle-DE3HAwpF.js","/assets/chart-column-DOftqM9U.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-l_Eh9jQG.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/EntityTypeIcon-BFRmw1TF.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/LibraryFunctionPreview-BYVx9KFp.js","/assets/SafeScreenshot-Bual6h18.js","/assets/loader-circle-DE3HAwpF.js","/assets/clock-DXui5oLF.js","/assets/search-BymWwY_X.js","/assets/file-text-fb2mx25c.js","/assets/chart-column-DOftqM9U.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-BCnOUEl9.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/useToast-XY00p4rI.js","/assets/LogViewer-CRcT5fOZ.js","/assets/EntityTypeIcon-BFRmw1TF.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/file-text-fb2mx25c.js","/assets/zap-Dra7vum1.js","/assets/circle-alert-0WShkwuc.js","/assets/SafeScreenshot-Bual6h18.js","/assets/chart-column-DOftqM9U.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-5579bc45.js",version:"5579bc45",sri:void 0},xm="build/client",bm="/",wm={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},vm=!0,Cm=!1,Nm=[],Sm={mode:"lazy",manifestPath:"/__manifest"},Am="/",Em={module:xs},_m={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Bo},"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:di},"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:fi},"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:sl},"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:ll},"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:_l},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Ml},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:pc},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:yc},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:wc},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Nc},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Ac},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Mc},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:kc},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Rc},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:jc},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:Wc},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Kc},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Jc},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:wd},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Nd},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Id},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:$d},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Fd},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Bd},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Wd},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Zd},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:eu},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:iu},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:hu},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Mu}};export{vo as A,bo as B,ce as C,Hs as D,Ks as E,He as F,js as G,Rr as H,Os as I,$r as J,zs as K,Us as L,xm as M,bm as N,wm as O,Rs as P,vm as Q,Cm as R,kn as S,Nm as T,Sm as U,Am as V,Em as W,_m as X,ym as Y,Ps as a,Xe as b,Ge as c,je as d,yt as e,Pn as f,Mn as g,Ir as h,Es as i,to as j,no as k,pt as l,ze as m,Lr as n,uo as o,Ot as p,et as q,Or as r,Fr as s,go as t,Qe as u,Yr as v,bt as w,yo as x,Jn as y,No as z};
|