@codeyam/codeyam-cli 0.1.0-staging.596f0eb → 0.1.0-staging.6e699e5
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 +8 -8
- package/analyzer-template/common/execAsync.ts +1 -1
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +10 -6
- package/analyzer-template/packages/ai/index.ts +10 -3
- package/analyzer-template/packages/ai/package.json +1 -1
- package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +128 -6
- package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +138 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +140 -6
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1239 -104
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +304 -0
- package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
- package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1501 -138
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +2 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +19 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +103 -6
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +23 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +42 -2
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
- package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +156 -0
- package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
- package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
- package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
- package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +6 -0
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1111 -91
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +207 -104
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +570 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +1977 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
- package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
- package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
- package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +276 -3
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +33 -3
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +7 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +90 -6
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
- package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
- package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +812 -0
- package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
- package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +123 -0
- package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +8 -1
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +14 -0
- package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +455 -267
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +18 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -7
- package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
- package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
- package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
- package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +265 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +588 -52
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +336 -133
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +156 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +461 -94
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
- package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
- package/analyzer-template/packages/aws/package.json +3 -3
- package/analyzer-template/packages/aws/s3/index.ts +1 -0
- package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
- package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
- package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
- package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
- package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
- package/analyzer-template/packages/database/src/lib/kysely/db.ts +4 -4
- package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
- package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
- package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +7 -3
- package/analyzer-template/packages/generate/index.ts +3 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
- package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
- package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
- package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/index.js +3 -0
- package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
- 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 +16 -1
- 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/generateScenarioClientWrapper.d.ts +9 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
- package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
- package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
- package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +196 -0
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
- package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
- package/analyzer-template/packages/process/index.ts +2 -0
- package/analyzer-template/packages/process/package.json +12 -0
- package/analyzer-template/packages/process/tsconfig.json +8 -0
- package/analyzer-template/packages/types/index.ts +5 -0
- package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
- package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
- package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
- package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +224 -0
- package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
- package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
- package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
- package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
- package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
- package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +196 -0
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
- package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
- package/analyzer-template/playwright/capture.ts +37 -18
- package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
- package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
- package/analyzer-template/playwright/takeScreenshot.ts +9 -7
- package/analyzer-template/playwright/waitForServer.ts +21 -6
- package/analyzer-template/project/analyzeBaselineCommit.ts +4 -0
- package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
- package/analyzer-template/project/analyzeFileEntities.ts +4 -0
- package/analyzer-template/project/analyzeRegularCommit.ts +4 -0
- package/analyzer-template/project/constructMockCode.ts +1181 -160
- package/analyzer-template/project/controller/startController.ts +16 -1
- package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
- package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
- package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
- package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +82 -36
- package/analyzer-template/project/orchestrateCapture.ts +36 -3
- package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
- package/analyzer-template/project/runAnalysis.ts +11 -0
- package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
- package/analyzer-template/project/serverOnlyModules.ts +194 -21
- package/analyzer-template/project/start.ts +26 -4
- package/analyzer-template/project/startScenarioCapture.ts +79 -41
- package/analyzer-template/project/writeMockDataTsx.ts +232 -57
- package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
- package/analyzer-template/project/writeScenarioComponents.ts +769 -181
- package/analyzer-template/project/writeScenarioFiles.ts +26 -0
- package/analyzer-template/project/writeSimpleRoot.ts +13 -15
- package/analyzer-template/scripts/comboWorkerLoop.cjs +1 -0
- package/analyzer-template/scripts/defaultCmd.sh +9 -0
- package/analyzer-template/tsconfig.json +2 -1
- package/background/src/lib/local/createLocalAnalyzer.js +1 -29
- package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
- package/background/src/lib/local/execAsync.js +1 -1
- package/background/src/lib/local/execAsync.js.map +1 -1
- package/background/src/lib/virtualized/common/execAsync.js +1 -1
- package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +2 -1
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
- package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js +2 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/constructMockCode.js +1053 -124
- package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
- package/background/src/lib/virtualized/project/controller/startController.js +11 -1
- package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
- package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
- package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
- package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
- package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
- package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +69 -32
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture.js +27 -4
- package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
- package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
- package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
- package/background/src/lib/virtualized/project/serverOnlyModules.js +163 -23
- package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
- package/background/src/lib/virtualized/project/start.js +21 -4
- package/background/src/lib/virtualized/project/start.js.map +1 -1
- package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
- package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +199 -50
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
- package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
- package/background/src/lib/virtualized/project/writeScenarioComponents.js +552 -125
- package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
- package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
- package/background/src/lib/virtualized/project/writeSimpleRoot.js +13 -13
- package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
- package/codeyam-cli/src/cli.js +7 -1
- package/codeyam-cli/src/cli.js.map +1 -1
- package/codeyam-cli/src/commands/analyze.js +1 -1
- package/codeyam-cli/src/commands/analyze.js.map +1 -1
- package/codeyam-cli/src/commands/baseline.js +174 -0
- package/codeyam-cli/src/commands/baseline.js.map +1 -0
- package/codeyam-cli/src/commands/debug.js +40 -18
- package/codeyam-cli/src/commands/debug.js.map +1 -1
- package/codeyam-cli/src/commands/default.js +0 -15
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/recapture.js +226 -0
- package/codeyam-cli/src/commands/recapture.js.map +1 -0
- package/codeyam-cli/src/commands/report.js +72 -24
- package/codeyam-cli/src/commands/report.js.map +1 -1
- package/codeyam-cli/src/commands/start.js +8 -12
- package/codeyam-cli/src/commands/start.js.map +1 -1
- package/codeyam-cli/src/commands/status.js +23 -1
- package/codeyam-cli/src/commands/status.js.map +1 -1
- package/codeyam-cli/src/commands/test-startup.js +1 -1
- package/codeyam-cli/src/commands/test-startup.js.map +1 -1
- package/codeyam-cli/src/commands/wipe.js +108 -0
- package/codeyam-cli/src/commands/wipe.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
- package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +31 -27
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- package/codeyam-cli/src/utils/analysisRunner.js +8 -13
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/backgroundServer.js +14 -4
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/database.js +91 -5
- package/codeyam-cli/src/utils/database.js.map +1 -1
- package/codeyam-cli/src/utils/generateReport.js +253 -106
- package/codeyam-cli/src/utils/generateReport.js.map +1 -1
- package/codeyam-cli/src/utils/git.js +79 -0
- package/codeyam-cli/src/utils/git.js.map +1 -0
- package/codeyam-cli/src/utils/install-skills.js +31 -17
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
- package/codeyam-cli/src/utils/queue/job.js +245 -16
- package/codeyam-cli/src/utils/queue/job.js.map +1 -1
- package/codeyam-cli/src/utils/queue/manager.js +25 -7
- package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
- package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
- package/codeyam-cli/src/utils/serverState.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +7 -5
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/versionInfo.js +25 -19
- package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
- package/codeyam-cli/src/utils/wipe.js +128 -0
- package/codeyam-cli/src/utils/wipe.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/database.js +98 -1
- package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
- package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
- package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/webserver/bootstrap.js +49 -0
- package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-BXhEawa3.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-efWKDYMr.js → EntityTypeBadge-DLqD3qNt.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Ba2JVPzP.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-C8lyxW9k.js +34 -0
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-aht4aafF.js +25 -0
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVtiBnY5.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-B0GLXMsr.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-xgeCVgSM.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-D4TZhLuw.js +21 -0
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DuDvi0jm.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-DEx02QDa.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-COPstp9J.js → TruncatedFilePath-DyFZkK0l.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/_index-BwqWJOgH.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DoLIqZX2.js +37 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.rules-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-Cx24_aWc.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chunk-EPOLDU6W-CXRTFQ3F.js +51 -0
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-BOARzkeR.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BdhJEx6B.js +21 -0
- package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BRb-0kQl.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-C2N4Op8e.js +23 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DavjRmOY.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D1T4TGjf.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-CTBG2mmz.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-CS2cb_eZ.js +29 -0
- package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DMJ7zii9.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-Cs4MdYtv.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-B4RJRvYB.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-commit-horizontal-CysbcZxi.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-DMUaGAqV.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-B1h680n5.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-lzqtyFU8.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-B7B9V-bu.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-f874c610.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/root-Bz5TunQg.js +57 -0
- package/codeyam-cli/src/webserver/build/client/assets/rules-hEkvVw2-.js +97 -0
- package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/search-CxXUmBSd.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-CS5f3WzT.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-DwFIBT09.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B6LgvRJg.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-C1v1PQzo.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-3pmpUQB-.js → useLastLogLine-aSv48UbS.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DYxHZQuP.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useToast-DEyawJ8r.js → useToast-mBRpZPiu.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-967OuJoF.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-DRTmerg9.js +257 -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/devServer.js +1 -3
- package/codeyam-cli/src/webserver/devServer.js.map +1 -1
- package/codeyam-cli/src/webserver/server.js +35 -25
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/templates/codeyam-power-rules-hook.sh +200 -0
- package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam:debug.md} +48 -4
- package/codeyam-cli/templates/codeyam:diagnose.md +650 -0
- package/codeyam-cli/templates/codeyam:new-rule.md +13 -0
- package/codeyam-cli/templates/codeyam:power-rules.md +447 -0
- package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam:setup.md} +139 -4
- package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam:sim.md} +1 -1
- package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam:test.md} +1 -1
- package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam:verify.md} +1 -1
- package/package.json +17 -16
- package/packages/ai/index.js +5 -4
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +99 -0
- package/packages/ai/src/lib/analyzeScope.js.map +1 -1
- package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
- package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +100 -1
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
- package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
- package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
- package/packages/ai/src/lib/astScopes/methodSemantics.js +97 -6
- package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
- package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
- package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
- package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/processExpression.js +945 -87
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/checkAllAttributes.js +24 -9
- package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
- package/packages/ai/src/lib/completionCall.js +178 -31
- package/packages/ai/src/lib/completionCall.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1198 -82
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +2 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +16 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +86 -4
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +20 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +34 -3
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
- package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructureChunking.js +111 -0
- package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
- package/packages/ai/src/lib/deepEqual.js +32 -0
- package/packages/ai/src/lib/deepEqual.js.map +1 -0
- package/packages/ai/src/lib/e2eDataTracking.js +241 -0
- package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
- package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
- package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
- package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateEntityDataStructure.js +5 -0
- package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +904 -84
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +186 -82
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +392 -0
- package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1440 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
- package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
- package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
- package/packages/ai/src/lib/isolateScopes.js +231 -4
- package/packages/ai/src/lib/isolateScopes.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +26 -3
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +6 -0
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
- package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +68 -6
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
- package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
- package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
- package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
- package/packages/ai/src/lib/resolvePathToControllable.js +667 -0
- package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
- package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
- package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
- package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
- package/packages/ai/src/lib/worker/analyzeScopeWorker.js +4 -0
- package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +15 -0
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/analysisContext.js +30 -5
- package/packages/analyze/src/lib/analysisContext.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
- package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
- package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +218 -50
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +10 -0
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -7
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
- package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
- package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
- package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
- package/packages/analyze/src/lib/files/enums/steps.js +1 -1
- package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +209 -0
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
- package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +458 -48
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +264 -78
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +96 -0
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +372 -89
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
- package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
- package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
- package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
- package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
- package/packages/database/src/lib/kysely/db.js +2 -2
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
- package/packages/generate/index.js +3 -0
- package/packages/generate/index.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
- package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
- package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
- package/packages/generate/src/lib/deepMerge.js +27 -1
- package/packages/generate/src/lib/deepMerge.js.map +1 -1
- package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
- package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
- package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
- package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
- package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/packages/process/index.js +3 -0
- package/packages/process/index.js.map +1 -0
- package/packages/process/src/GlobalProcessManager.js.map +1 -0
- package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
- package/packages/process/src/ProcessManager.js.map +1 -0
- package/packages/process/src/index.js.map +1 -0
- package/packages/process/src/managedExecAsync.js.map +1 -0
- package/packages/types/index.js.map +1 -1
- package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/packages/utils/src/lib/safeFileName.js +29 -3
- package/packages/utils/src/lib/safeFileName.js.map +1 -1
- package/scripts/finalize-analyzer.cjs +6 -4
- package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
- package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
- package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
- package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
- package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
- package/analyzer-template/process/README.md +0 -507
- package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
- package/background/src/lib/process/ProcessManager.js.map +0 -1
- package/background/src/lib/process/index.js.map +0 -1
- package/background/src/lib/process/managedExecAsync.js.map +0 -1
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CVbSvOjo.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-DcwcHyl5.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-WgwC1GfJ.js +0 -26
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-IEKom9O2.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-BYnfxbUG.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-_lBPJCzG.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-lHVhvsu_.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-d_TBk4GQ.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/_index-kGT7VUqj.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DDGmhu7P.js +0 -7
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-n_HPRfM_.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CbVoyx1U.js +0 -26
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-D1VOYveA.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-YR8jjAlu.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-B8vP3V_s.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-CN6aLCT1.js +0 -16
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DA5Jeu2P.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BTeitalf.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-du6UEYD-.js +0 -13
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-BpjkhMoi.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/files-BQGvk4lJ.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-DVdYRT-I.js +0 -12
- package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/index-DCG-vks0.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-GazdNeLl.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-0b694d28.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/root-D3tQP7hx.js +0 -16
- package/codeyam-cli/src/webserver/build/client/assets/search-CIY6XmtE.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/settings-CoMDgElu.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/simulations-agkniXp2.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B2VUcygF.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-EvdK-zXP.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-DGVHQEXD.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-CghkTkIL.js +0 -166
- package/codeyam-cli/templates/debug-command.md +0 -303
- package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
- package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
- package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/isFrontend.js +0 -5
- package/packages/ai/src/lib/isFrontend.js.map +0 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
- package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
- /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
- /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
- /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
- /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
- /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
var Cs=Object.defineProperty;var ua=e=>{throw TypeError(e)};var Ns=(e,t,r)=>t in e?Cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var an=(e,t,r)=>Ns(e,typeof t!="symbol"?t+"":t,r),Ss=(e,t,r)=>t.has(e)||ua("Cannot "+r);var ma=(e,t,r)=>(Ss(e,t,"read from private field"),r?r.call(e):t.get(e)),ha=(e,t,r)=>t.has(e)?ua("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as c,Fragment as ce}from"react/jsx-runtime";import{PassThrough as Es}from"node:stream";import{createReadableStreamFromReadable as As}from"@react-router/node";import{ServerRouter as ks,useFetcher as Ee,useLocation as En,useNavigate as It,Link as ae,UNSAFE_withComponentProps as Oe,Meta as Ps,Links as Ms,ScrollRestoration as _s,Scripts as Ts,useLoaderData as We,useRevalidator as nt,Outlet as Is,data as U,useSearchParams as Jt,useParams as eo,useActionData as $s}from"react-router";import{isbot as js}from"isbot";import{renderToPipeableStream as Rs}from"react-dom/server";import{useState as M,useEffect as ne,useCallback as se,createContext as gr,useContext as An,useRef as Se,useMemo as oe}from"react";import{Settings as pa,CheckCircle2 as yr,Bug as to,AlertTriangle as sr,Check as no,Copy as ro,Loader2 as Ze,HomeIcon as Ds,GitCommitIcon as fa,File as Ls,RefreshCw as Fs,BookOpen as Os,SettingsIcon as Ys,PanelsTopLeftIcon as zs,ComponentIcon as Bs,FileText as ga,Code as ya,Box as Us,List as Ws,BarChart3 as Hs,Tag as qs,Image as Wt,Code2 as ao,Activity as Hn,ChevronDown as Ct,CircleEqual as Gs,Pause as Js,ListTodo as Vs,PauseCircle as Qs,FileCode as Ks,GripVertical as Zs,Ban as Xs,CheckCircle as ei,Search as oo,FolderOpen as ti,CodeXml as ni,Zap as ri,Plus as ir,FolderTree as xa,Filter as ai,X as oi,Terminal as si,ChevronRight as xr,Save as ii,Eye as ba,GitCommit as li,EyeOff as ci,FileEdit as di,Minus as ui,Pencil as so,Clock as mi,Trash2 as hi}from"lucide-react";import"fetch-retry";import pi from"better-sqlite3";import{Pool as fi}from"pg";import*as Q from"fs";import Nt,{existsSync as gi}from"fs";import*as ee from"path";import pe from"path";import{OperationNodeTransformer as yi,Kysely as io,ParseJSONResultsPlugin as xi,SqliteDialect as bi,PostgresDialect as vi,sql as Qe}from"kysely";import*as wi from"kysely/helpers/sqlite";import*as Ci from"kysely/helpers/postgres";import Pe from"typescript";import*as Ie from"fs/promises";import xe,{writeFile as Ni,readFile as Si}from"fs/promises";import*as Ei from"os";import lr from"os";import Ai from"prompts";import pn from"chalk";import*as ki from"crypto";import br,{randomUUID as Vt}from"crypto";import{execSync as Me,spawn as kn,exec as vr}from"child_process";import{fileURLToPath as wr}from"url";import{promisify as Cr}from"util";import Pi from"dotenv";import Mi,{EventEmitter as _i}from"events";import{v4 as Ti}from"uuid";import Ii from"openai";import $i from"p-queue";import va from"p-retry";import{DynamoDBClient as Pn,PutItemCommand as ji}from"@aws-sdk/client-dynamodb";import{LRUCache as Nr}from"lru-cache";import"pluralize";import"piscina";import Ri from"json5";import{marshall as Di}from"@aws-sdk/util-dynamodb";import{Prism as Li}from"react-syntax-highlighter";import{vscDarkPlus as Fi}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Oi}from"node:crypto";import Yi from"v8";import zi from"react-markdown";import Bi from"react-diff-viewer-continued";const lo=5e3;function Ui(e,t,r,a,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((s,i)=>{let l=!1,d=e.headers.get("user-agent"),m=d&&js(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),lo+1e3);const{pipe:h,abort:p}=Rs(n(ks,{context:a,url:e.url}),{[m](){l=!0;const f=new Es({final(y){clearTimeout(u),u=void 0,y()}}),g=As(f);r.set("Content-Type","text/html"),h(f),s(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const Wi=Object.freeze(Object.defineProperty({__proto__:null,default:Ui,streamTimeout:lo},Symbol.toStringTag,{value:"Module"}));function Hi({id:e,selected:t,onClick:r,icon:a,name:o}){const[s,i]=M(!1);ne(()=>{i(!0)},[]);const l=se(()=>{r==null||r(e)},[r,e]);return c("button",{className:`
|
|
2
|
+
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
+
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
+
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
+
`,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:s&&a}),n("span",{className:`text-[9px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:o})]})}const co="/assets/cy-logo-cli-CCKUIm0S.svg";function qi(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function Gi({content:e,className:t=""}){const[r,a]=M(!1),o=se(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(s=>{console.error("Failed to copy:",s)})},[e]);return n("button",{onClick:o,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?c(ce,{children:[n(no,{size:14}),"Copied"]}):c(ce,{children:[n(ro,{size:14}),"Copy"]})})}function uo({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:o}){const[s,i]=M(""),[l,d]=M(a),[m,u]=M(!1),[h,p]=M(!1),[f,g]=M(null),[y,x]=M(null),b=Ee(),v=b.state!=="idle",w=!!(r.scenarioId||r.analysisId),C=r.analysisId||r.scenarioId||"",E=()=>{const T=`/codeyam:diagnose ${C}`;return s.trim()?`${T} ${s.trim()}`:T};if(b.data&&!h&&!y){const T=b.data;T.success&&T.reportId?(p(!0),g(T.reportId)):T.error&&x(T.error)}const S=async()=>{x(null);const T=new FormData;if(T.append("issueType","other"),T.append("description",s),T.append("email",l),T.append("source",r.source),T.append("entitySha",r.entitySha||""),T.append("scenarioId",r.scenarioId||""),T.append("analysisId",r.analysisId||""),T.append("currentUrl",r.currentUrl),T.append("entityName",r.entityName||""),T.append("entityType",r.entityType||""),T.append("scenarioName",r.scenarioName||""),T.append("errorMessage",r.errorMessage||""),o)try{const D=await(await fetch(o)).blob();T.append("screenshot",D,"screenshot.jpg")}catch($){console.error("Failed to convert screenshot:",$)}b.submit(T,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},A=()=>{i(""),u(!1),p(!1),g(null),x(null),t()},k=T=>{T.key==="Escape"&&A()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:k,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[v?n("div",{className:"animate-spin",children:n(pa,{size:24,style:{strokeWidth:1.5}})}):h?n(yr,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(to,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:A,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?c("div",{children:[c("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),c("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:A,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:qi(r)}),n("button",{type:"button",onClick:()=>u(!m),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:m?"Hide":"Details"})]}),m&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),o&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:s,onChange:T=>i(T.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),w&&c(ce,{children:[c("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),c("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:E()}),n(Gi,{content:E(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),c("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),c("div",{className:w?"opacity-75":"",children:[w&&c("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:T=>d(T.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),c("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(sr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),v&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),y&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(sr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:A,disabled:v,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void S(),disabled:v,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:v?c(ce,{children:[n("div",{className:"animate-spin",children:n(pa,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})]})}):null}const wa={source:"navbar"},Sr=gr(void 0);function Ji({children:e}){const[t,r]=M(wa),a=se(s=>{r(s)},[]),o=se(()=>{r(wa)},[]);return n(Sr.Provider,{value:{contextData:t,setContextData:a,resetContextData:o},children:e})}function mt(e){const t=An(Sr),r=Se(t);ne(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function Vi(){const e=An(Sr),t=En();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function Qi(){var v;const e=En(),t=It(),[r,a]=M(),[o,s]=M(!1),[i,l]=M(!1),[d,m]=M(null),u=Ee();ne(()=>{u.state==="idle"&&!u.data&&u.load("/api/generate-report")},[u]);const h=((v=u.data)==null?void 0:v.defaultEmail)||"",p={width:"20px",height:"20px",strokeWidth:1.5},f=[{id:"dashboard",icon:n(Ds,{style:p}),link:"/",name:"Dashboard"},{id:"simulations",icon:c("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:p,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(fa,{style:p}),link:"/git",name:"Git"},{id:"files",icon:n(Ls,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:n(Fs,{style:p}),link:"/activity",name:"Activity"},{id:"rules",icon:n(Os,{style:p}),link:"/rules",name:"Rules"},{id:"settings",icon:n(Ys,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:n(fa,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(zs,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Bs,{style:p}),link:"/components",name:"Components",hidden:!0}],g=se(w=>{const C=f.find(E=>E.id===w);C!=null&&C.link&&t(C.link),a(E=>E===w?void 0:w)},[f,t]);ne(()=>{const w={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],rules:["rules"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[C,E]of Object.entries(w))if(E.some(S=>S==="/"?e.pathname==="/":e.pathname.includes(S))){a(C);return}a(void 0)},[e]);const y=async()=>{l(!0);try{const{default:w}=await import("html2canvas-pro"),E=(await w(document.body)).toDataURL("image/jpeg",.8);m(E),s(!0)}catch(w){console.error("Screenshot capture failed:",w),s(!0)}finally{l(!1)}},x=()=>{s(!1),m(null)},b=Vi();return c(ce,{children:[c("div",{id:"sidebar",className:"relative w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(ae,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:co,alt:"CodeYam",className:"h-6"})})}),f.filter(w=>!w.hidden).map(w=>n(Hi,{id:w.id,selected:w.id===r,onClick:g,icon:w.icon,name:w.name},`sidebar-button-${w.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void y(),disabled:i,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:i?n(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(to,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:i?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),o&&n(uo,{isOpen:!0,onClose:x,context:b,defaultEmail:h,screenshotDataUrl:d??void 0})]})}const mo=gr(void 0);function Ki({children:e}){const[t,r]=M([]),a=se((s,i="info",l=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:s,type:i,duration:l};r(u=>[...u,m])},[]),o=se(s=>{r(i=>i.filter(l=>l.id!==s))},[]);return n(mo.Provider,{value:{toasts:t,showToast:a,closeToast:o},children:e})}function Er(){const e=An(mo);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Zi({toast:e,onClose:t}){ne(()=>{const o=e.duration||5e3;if(o>0){const s=setTimeout(()=>{t(e.id)},o);return()=>clearTimeout(s)}},[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 Xi({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
+
@keyframes slideIn {
|
|
8
|
+
from {
|
|
9
|
+
transform: translateX(400px);
|
|
10
|
+
opacity: 0;
|
|
11
|
+
}
|
|
12
|
+
to {
|
|
13
|
+
transform: translateX(0);
|
|
14
|
+
opacity: 1;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
`}),e.map(r=>n(Zi,{toast:r,onClose:t},r.id))]})}function ht(e,t){const[r,a]=M(""),[o,s]=M(!1),[i,l]=M(null),[d,m]=M(!1);ne(()=>{t&&(m(!1),s(!1),l(null))},[t]),ne(()=>{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(`
|
|
18
|
+
`).filter(v=>v.length>0);if(y.length<3){s(!1),m(!1),l(null),a("");return}const x=y.filter(v=>v.includes("CodeYam Log Level 1"));if(x.length>0){const v=x[x.length-1];a(v.replace(/.*CodeYam Log Level 1: /,""))}const b=y.find(v=>v.includes("$$INTERACTIVE_SERVER_URL$$:"));if(b){const v=b.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(v),m(!0)}y.some(v=>v.includes("CodeYam: Exiting start.js"))&&s(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=se(()=>{a(""),s(!1),l(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:o,resetLogs:u}}function dt({projectSlug:e,onClose:t}){const[r,a]=M("Loading logs..."),[o,s]=M(!0),[i,l]=M(!0),[d,m]=M("all"),u=Se(null);return ne(()=>{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(`
|
|
19
|
+
`).filter(y=>{if(y.length===0)return!1;const x=y.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
+
`))}i&&u.current&&setTimeout(()=>{var g;(g=u.current)==null||g.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),o){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,o,i,d]),ne(()=>{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:o,onChange:h=>s(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 Ue({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},a=r[e]||r.other,o=t==="large"?18:14,s=t==="large"?32:18,i=()=>{switch(e){case"library":return n(ao,{size:o,color:a.iconColor});case"visual":return n(Wt,{size:o,color:a.iconColor});case"type":return n(qs,{size:o,color:a.iconColor});case"data":return n(Hs,{size:o,color:a.iconColor});case"index":return n(Ws,{size:o,color:a.iconColor});case"functionCall":return n(ya,{size:o,color:a.iconColor});case"class":return n(Us,{size:o,color:a.iconColor});case"method":return n(ya,{size:o,color:a.iconColor});case"other":return n(ga,{size:o,color:a.iconColor});default:return n(ga,{size:o,color:a.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${s}px`,height:`${s}px`},children:i()})}function ho({filePath:e,maxLength:t=60,className:r,style:a}){const s=((l,d)=>{if(l.length<=d)return l;const m="...",u=d-m.length,h=Math.ceil(u*.4),p=Math.floor(u*.6),f=l.slice(0,h),g=l.slice(-p),y=f.lastIndexOf("/"),x=g.indexOf("/"),b=y>h*.5?f.slice(0,y+1):f,v=x!==-1&&x<p*.5?g.slice(x):g;return`${b}${m}${v}`})(e,t),i=s!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:s})}function qn({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:o=!1,scenarioCount:s=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(Ue,{type:e.entityType||"other"}),c(ae,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&s>0&&` (${s})`]}),n(ho,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Gn={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function el({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:o=0,queueJobs:s=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var I,O,V;const[d,m]=M(!1),[u,h]=M(!1),[p,f]=M(null),[g,y]=M(new Set),[x,b]=M(new Set),[v,w]=M(!1),C=!!i||s.length>0,E=!!i,S=(i==null?void 0:i.entities)||r;e!=null&&e.analysisCompletedAt,e==null||e.readyToBeCaptured,e==null||e.capturesCompleted;const A=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,k=C,{lastLine:T}=ht(t,k),$=E||s.length>0,D=new Set(((I=i==null?void 0:i.entities)==null?void 0:I.map(R=>R.sha))||[]),P=l.filter(R=>!(R.currentEntityShas||[]).some(L=>D.has(L))),_=(()=>{const F=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&A){const L=e.analysisCompletedAt||e.createdAt;if(new Date(L).getTime()>F)return!0}if(P.length>0){const L=P[0],G=L.analysisCompletedAt||L.archivedAt||L.createdAt;if(G&&new Date(G).getTime()>F)return!0}return!1})();return ne(()=>{const R=(i==null?void 0:i.id)||null;C&&!u&&R!==p&&h(!0),!C&&p!==null&&f(null)},[C,i==null?void 0:i.id,u,p]),c(ce,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&c("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[$?n(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Hn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity: No Activity Yet"}),$&&n("button",{onClick:R=>{R.stopPropagation(),m(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[$?n(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Hn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>m(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(Ct,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[$&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Hn,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:S.length>0?c("div",{className:"space-y-1.5",children:[(v?S:S.slice(0,3)).map(R=>n(qn,{entity:R,nameSize:"11px",pathSize:"10px",pathMaxLength:150},R.sha)),S.length>3&&n("button",{onClick:()=>w(R=>!R),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gn,"aria-label":v?"Show fewer entities":`Show ${S.length-3} more entities`,children:v?"Show less":`+${S.length-3} more`}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((R,F)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:R},F)),i.entityNames.length>5&&c("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):c("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((O=i.entityShas)==null?void 0:O.length)||0," ",((V=i.entityShas)==null?void 0:V.length)===1?"entity":"entities","..."]}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]})})]}),s.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Gs,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:s.map(R=>{var G,j;const F=g.has(R.id),L=F?R.entities:R.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:R.entities.length>0?c("div",{className:"space-y-1.5",children:[L.map(N=>n(qn,{entity:N,nameSize:"10px",pathSize:"9px",pathMaxLength:120},N.sha)),R.entities.length>3&&n("button",{onClick:()=>{y(N=>{const z=new Set(N);return z.has(R.id)?z.delete(R.id):z.add(R.id),z})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gn,"aria-label":F?"Show fewer entities":`Show ${R.entities.length-3} more entities`,children:F?"Show less":`+${R.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[R.type==="analysis"&&n(ce,{children:R.entityNames&&R.entityNames.length>0?c("div",{className:"space-y-0.5",children:[R.entityNames.slice(0,5).map((N,z)=>n("div",{children:N},z)),R.entityNames.length>5&&c("div",{className:"italic",children:["+",R.entityNames.length-5," more"]})]}):`Analyzing ${((G=R.entityShas)==null?void 0:G.length)||0} ${((j=R.entityShas)==null?void 0:j.length)===1?"entity":"entities"}`}),R.type==="recapture"&&"Recapturing scenario",R.type==="debug-setup"&&"Setting up debug environment"]})},R.id)})})]}),_&&P.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(yr,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:P.slice(0,3).map((R,F)=>{const L=R.entities||[],G=R.analysisCompletedAt||R.archivedAt||R.createdAt||"",j=(()=>{if(!G)return"";const H=Date.now()-new Date(G).getTime(),re=Math.floor(H/6e4),J=Math.floor(H/36e5);return J>0?`${J}h ago`:re>0?`${re}m ago`:"just now"})(),N=x.has(F),W=(N?L:L.slice(0,3)).map(H=>{var re,J,Y;return{...H,scenarioCount:((Y=(J=(re=H.analyses)==null?void 0:re[0])==null?void 0:J.scenarios)==null?void 0:Y.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:L.length>0&&c("div",{className:"space-y-1.5",children:[W.map((H,re)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(qn,{entity:H,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:H.scenarioCount})}),re===0&&j&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:j})]},H.sha)),L.length>3&&n("button",{onClick:()=>{b(H=>{const re=new Set(H);return re.has(F)?re.delete(F):re.add(F),re})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gn,"aria-label":N?"Show fewer entities":`Show ${L.length-3} more entities`,children:N?"Show less":`+${L.length-3} more`})]})},F)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(ae,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(dt,{projectSlug:t,onClose:()=>m(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Qt(e){const{file_id:t,project_id:r,commit_id:a,file_path:o,entity_type:s,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(rt):void 0,g=d?kt(d):void 0;return He({...h,fileId:t,projectId:r,commitId:a,filePath:o,entityType:s,commit:g,analyses:f,branchIds:p,createdAt:m,updatedAt:u})}function Ar(e){return He({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function kr(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:o,created_at:s,updated_at:i,github_token:l,configuration:d,team_id:m,...u}=e;return He({...u,branches:t?t.map(Tt):void 0,files:r?r.map(Ar):void 0,analyzedAt:a,contentChangedAt:o,createdAt:s,updatedAt:i})}function tl(e){const{id:t,project_id:r,user_id:a,scenario_id:o,thumbs_up:s,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:o,thumbsUp:!!s,user:l})}function nl(e){const{id:t,project_id:r,user_id:a,scenario_id:o,text:s,created_at:i,updated_at:l,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:o,text:s,createdAt:i,updatedAt:l,user:m})}function po(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:o,user_scenarios:s,scenario_comments:i,approved:l,...d}=e,m=o?rt(o):void 0,u=s?s.map(tl):void 0,h=i?i.map(nl):void 0;return He({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:m,userScenarios:u,comments:h})}function rl(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?rt(e.analysis):void 0,entity:e.entity?Qt(e.entity):void 0,branch:e.branch?Tt(e.branch):void 0,createdAt:e.created_at})}function rt(e){const{project_id:t,commit_id:r,file_id:a,file_path:o,entity_sha:s,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:x,branch_commit_sha:b,committed_at:v,completed_at:w,created_at:C,updated_at:E,indirect:S,...A}=e,k=u?Qt(u):void 0,T=m?Ar(m):void 0,$=p?kr(p):void 0,D=h?kt(h):void 0,P=f?f.map(po):void 0,_=g?g.map(rl):void 0,I=_?_.map(O=>O.branch):void 0;return He({...A,projectId:t,commitId:r,fileId:a,filePath:o,entitySha:s,entityType:i,entityName:l,previousAnalysisId:d,entity:k,file:T,commit:D,project:$,scenarios:P,analysisBranches:_,branches:I,dependencyAnalyzedTreeSha:y,analyzedTreeSha:x,branchCommitSha:b,committedAt:v,completedAt:w,createdAt:C,updatedAt:E,indirect:!!S})}function Pr(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?kt(e.commit):void 0,branch:e.branch?Tt(e.branch):void 0})}function al(e){const{project_id:t,commit_id:r,created_at:a,updated_at:o,success:s,...i}=e;return He({...i,projectId:t,commitId:r,createdAt:a,updatedAt:o,success:!!s})}function kt(e){const{project_id:t,branch_id:r,branch:a,background_jobs:o,merged_branch_id:s,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,x=a?Tt(a):void 0,b=i?Tt(i):void 0,v=(o==null?void 0:o.length)>0?al(o[o.length-1]):void 0,w=(u??[]).map(rt),C=(h??[]).map(Qt),E=(p==null?void 0:p.length)>0?p.map(Pr):void 0;return m&&(m.username=m.preferredUsername??m.username),He({...y,projectId:t,branchId:r,branch:x,backgroundJob:v,mergedBranchId:s,mergedBranch:b,aiMessage:l,htmlUrl:d,author:m,analyses:w,entities:C,commitBranches:E,committedAt:f,analyzedAt:g})}function Tt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:o,active_at:s,created_at:i,updated_at:l,primary:d,...m}=e,u=a?a.map(kt):void 0,h=o?o.flatMap(p=>rt(p.analysis)):void 0;return He({...m,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:s,createdAt:i,updatedAt:l,primary:!!d})}var Sn;class ol{constructor(){ha(this,Sn,new sl)}transformQuery(t){return ma(this,Sn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Sn=new WeakMap;class sl extends yi{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const X=()=>null,il={analyzed_at:X(),configuration:X(),content_changed_at:X(),created_at:X(),description:X(),github_token:X(),id:X(),metadata:X(),name:X(),path:X(),slug:X(),team_id:X(),updated_at:X()},ll=Object.keys(il),cl={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},dl=Object.keys(cl),ul={active_at:X(),content_changed_at:X(),created_at:X(),id:X(),metadata:X(),name:X(),primary:X(),project_id:X(),ref:X(),sha:X(),updated_at:X()},fo=Object.keys(ul),ml={ai_message:X(),analyzed_at:X(),author_github_username:X(),branch_id:X(),committed_at:X(),created_at:X(),files:X(),html_url:X(),id:X(),merged_branch_id:X(),message:X(),metadata:X(),project_id:X(),sha:X(),title:X(),url:X()},hl=Object.keys(ml),pl={commit_id:X(),created_at:X(),description:X(),documentation:X(),entity_type:X(),file_id:X(),file_path:X(),metadata:X(),name:X(),project_id:X(),quality:X(),sha:X(),updated_at:X()},go=Object.keys(pl),fl={active:X(),branch_id:X(),entity_sha:X()},gl=Object.keys(fl),yl={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},xl=Object.keys(yl),bl={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},Mr=Object.keys(bl),vl=!!St("ENABLE_QUERY_LOGGING"),wl=!!St("ENABLE_QUERY_ERROR_LOGGING");St("USE_LOCAL_POSTGRESQL_FOR_TESTING");let on;function be(){if(!on){const e=xo();if(e==="sqlite")on=Cl();else if(e==="postgresql")on=Nl();else throw new Error(`Unknown database type: ${e}`)}return on}function Cl(e){if(e||(e=St("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=Q.existsSync(e),r=ee.dirname(e);if(!Q.existsSync(r))Q.mkdirSync(r,{recursive:!0,mode:493});else try{Q.chmodSync(r,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const a=new pi(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const o=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&o.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(o){console.error("CodeYam DB ERROR: Failed to verify database schema:",o)}return new io({dialect:new bi({database:a}),plugins:[new xi,new ol],log:yo})}function Nl(){const e=El();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new fi({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new io({dialect:new vi({pool:t}),log:yo})}let Jn=null;function Pt(){return Jn||(Jn=Sl(xo())),Jn}function yo(e){e.level==="error"?wl&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):vl&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Sl(e){if(e==="sqlite")return wi;if(e==="postgresql")return Ci;throw new Error(`Unknown database type: ${e}`)}function xo(){if(St("SQLITE_PATH"))return"sqlite";if(St("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function El(){const e=St("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function St(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var Kt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Kt||{});const Mn="Default Scenario";let Al="<main>";function kl(){return Al}function Ca(e,...t){fe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function fe(...e){const t=kl(),r=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
21
|
+
${o.stack}`:typeof o=="object"?Pl(o):String(o)}).filter(Boolean).join(`
|
|
22
|
+
`),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
23
|
+
`);return}console.log(a.replace(/\n/g,"\r"))}function Pl(e,t=2){function r(a,o=new WeakMap){return a===null||typeof a!="object"?a:o.has(a)?`"[Circular: ${a.constructor.name}]"`:(o.set(a,!0),Array.isArray(a)?`[${a.map(l=>{const d=r(l,o);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,o):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 o=r(e);if(!t)return o;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(s){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:s,pureStringifyError:a,serialized:o}),o}}}function fn(e,t){try{let r=function(s){var i,l;if(Pe.isFunctionDeclaration(s)&&Ot(s)){const d=((i=s.name)==null?void 0:i.text)||"default",m=s.getText(a),u=Vn(s);o.push({name:d,code:m,sha:yt(t,d,m),entityType:"function",isDefault:u})}else if(Pe.isClassDeclaration(s)&&Ot(s)){const d=((l=s.name)==null?void 0:l.text)||"default",m=s.getText(a),u=Vn(s),h=m.includes("React.")||m.includes("jsx")||m.includes("tsx");o.push({name:d,code:m,sha:yt(t,d,m),entityType:h?"component":"class",isDefault:u})}else if(Pe.isInterfaceDeclaration(s)&&Ot(s)){const d=s.name.text,m=s.getText(a);o.push({name:d,code:m,sha:yt(t,d,m),entityType:"interface",isDefault:!1})}else if(Pe.isTypeAliasDeclaration(s)&&Ot(s)){const d=s.name.text,m=s.getText(a);o.push({name:d,code:m,sha:yt(t,d,m),entityType:"type",isDefault:!1})}else if(Pe.isVariableStatement(s)&&Ot(s)){const d=Vn(s);s.declarationList.declarations.forEach(m=>{var u;if(Pe.isIdentifier(m.name)){const h=m.name.text,p=s.getText(a),f=((u=m.initializer)==null?void 0:u.getText(a))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));o.push({name:h,code:p,sha:yt(t,h,p),entityType:g?"component":"variable",isDefault:d})}})}else if(Pe.isExportAssignment(s)){const d=s.getText(a);o.push({name:"default",code:d,sha:yt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Pe.isExportDeclaration(s)&&s.exportClause&&Pe.isNamedExports(s.exportClause)){const d=s.getText(a);for(const m of s.exportClause.elements){const u=m.name.text;o.push({name:u,code:d,sha:yt(t,u,d),entityType:"unknown",isDefault:!1})}}Pe.forEachChild(s,r)};const a=Pe.createSourceFile(t,e,Pe.ScriptTarget.Latest,!0),o=[];return r(a),o}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Ot(e){if(!Pe.canHaveModifiers(e))return!1;const t=Pe.getModifiers(e);return t?t.some(r=>r.kind===Pe.SyntaxKind.ExportKeyword):!1}function Vn(e){if(!Pe.canHaveModifiers(e))return!1;const t=Pe.getModifiers(e);return t?t.some(r=>r.kind===Pe.SyntaxKind.DefaultKeyword):!1}function yt(e,t,r){const a=br.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function Ml(e){var m;const{webapp:t,port:r,environmentVariables:a,packageManager:o}=e,s=t==null?void 0:t.startCommand;if(!s)return`${o} ${o==="npm"?"run ":""}dev`;const i=((m=s.args)==null?void 0:m.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of a)if(u.key&&u.value!==void 0){const h=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${h}'`)}if(s.env)for(const[u,h]of Object.entries(s.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return s.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${s.command} ${i.join(" ")}`}function _l(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=ee.normalize(e),a=[...t].sort((o,s)=>{var i,l;return(((i=s.path)==null?void 0:i.length)??0)-(((l=o.path)==null?void 0:l.length)??0)});for(const o of a){const s=ee.normalize(o.path??".");if(s==="."||r.startsWith(s+ee.sep)||r===s)return o}return t[0]}function Tl(e){const{filePath:t,webapps:r,environmentVariables:a,port:o,packageManager:s}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=_l(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Ml({webapp:i,port:o,environmentVariables:a,packageManager:s});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??s,startCommand:l,url:`http://localhost:${o}/static/codeyam-sample`}}function _n(e,t,r=[]){const a=Array.isArray(t)?t:[t];return o=>o.columns(a).doUpdateSet(s=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,s.ref(`excluded.${l}`)]))})}function Il(e){const{jsonObjectFrom:t}=Pt();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 $l({ids:e,analysisId:t}){const r=be();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 fe("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 fe("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function jl(...e){try{const t=br.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 Na(e,t){return t.map(r=>Rl(e,r))}function Rl(e,t){return Qe` ${Qe.ref(e)}.${Qe.ref(t)}`.as(t)}function Dl(e,t,r){return t.map(a=>Ll(e,a,r))}function Ll(e,t,r){return Qe` ${Qe.ref(e)}.${Qe.ref(t)}`.as(`_cy_${r}:${t}`)}function Fl(e,...t){const r={};for(const[a,o]of Object.entries(e)){const s=a.match(/^_cy_(.+?):(.+)$/);if(s){const[,i,l]=s;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=o}return r}const Ol=50;function Yl(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 Sa({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:o,commitIds:s,branchCommitSha:i,limit:l}){const d=be(),{jsonObjectFrom:m,jsonArrayFrom:u}=Pt();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(s){if(s.length===0)return null;h=h.where("commit_id","in",s)}return a&&(h=h.where("entity_name","=",a)),o&&(h=h.where("entity_sha","in",o)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),d.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[m(p.selectFrom("entities").select(Na("entities",go)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),u(p.selectFrom("scenarios").select(Na("scenarios",Mr)).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 ut(e){const{ids:t,fileIds:r,entityShas:a,commitIds:o}=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:o,key:"commitIds"}}).find(([d,{arr:m}])=>(m==null?void 0:m.length)>0);let l=[];if(i){const[d,{arr:m,key:u}]=i,h=Yl(m,Ol),p=[];for(let f=0;f<h.length;f++){const g=h[f],x=await Sa({...e,[u]:g}).execute();x&&p.push(...x)}l=p}else{const m=await Sa(e).execute();if(!m||m.length===0)return fe("CodeYam: No analyses found",null,e),null;l=m}return l.length===0?null:l.map(rt)}catch(s){return fe("CodeYam Error: Database error in loadAnalyses",s,e),null}}function zl(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=Pt();let o=e.selectFrom("analysis_branches").select(dl).select(s=>a(s.selectFrom("branches").select(fo).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(o=t(o)),r(o)}async function at({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}){const f=be();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)),s&&(g=g.where("entity_name","=",s)),o?g=g.where("commit_id","=",o):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:x}=Pt();g=g.select(v=>{const w=[];return w.push(y(v.selectFrom("entities").select(go).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&w.push(y(v.selectFrom("files").select(xl).whereRef("files.id","=","analyses.file_id")).as("file")),m&&w.push(y(v.selectFrom("projects").select(ll).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&w.push(x(v.selectFrom("scenarios").select(Mr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&w.push(zl(v,C=>C.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&w.push(y(v.selectFrom("commits").select(hl).select(C=>Il(C).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),w});const b=await g.executeTakeFirst();return b?rt(b):(fe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null)}catch(g){return fe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null}}async function bo({projectId:e,ids:t,names:r,includeInactive:a}){const o=be();try{let s=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];s=s.where("id","in",t)}if(r){if(r.length===0)return[];s=s.where("name","in",r)}return a||(s=s.where("active_at","is not",null)),(await s.execute()).map(Tt)}catch(s){return fe("CodeYam Error: Database error loading branches",s,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function Bl({projectId:e,commitId:t,branchId:r,active:a,includeBranches:o}){const s=be();try{let i=s.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,m=>m.select(Dl("branches",fo,"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=>Fl(m,"branch")).map(Pr)}catch(i){return fe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:o}),null}}async function Ul(e){if(e.length===0)return new Map;const t=be();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(s=>{s.branch_id&&a.add(s.branch_id),s.merged_branch_id&&a.add(s.merged_branch_id)}),a.size===0)return new Map;const o=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(o.map(s=>[s.id,s]))}catch(r){return fe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Wl(e){if(e.length===0)return new Map;const t=be(),{jsonObjectFrom:r,jsonArrayFrom:a}=Pt();try{const o=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(Mr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),s=new Map;return o.forEach(i=>{const l=s.get(i.commit_id)||[];l.push(i),s.set(i.commit_id,l)}),s}catch(o){return fe("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function Hl(e){if(e.length===0)return new Map;const t=be();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(o=>{const s=a.get(o.commit_id)||[];s.push(o),a.set(o.commit_id,s)}),a}catch(r){return fe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function gn({projectId:e,branchId:t,ids:r,shas:a,fileNames:o,limit:s=10}){if(!e&&!r)throw new Error("Must provide projectId or ids");const i=be(),{jsonObjectFrom:l}=Pt();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(o&&o.length>0){const y=Qe.join(o.map(x=>Qe`${x}`),Qe`, `);d=d.where(Qe`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${Qe.ref("commits.files")}) AS f
|
|
27
|
+
WHERE json_extract(f.value, '$.fileName') IN (${y})
|
|
28
|
+
)
|
|
29
|
+
`)}t&&(d=d.where("branch_id","=",t));const m=await d.orderBy("committed_at","desc").limit(s).execute();if(!m||m.length===0)return[];const u=m.map(y=>y.id),[h,p,f]=await Promise.all([Ul(u),Wl(u),Hl(u)]);return m.map(y=>{const x=y.branch_id?h.get(y.branch_id):void 0,b=y.merged_branch_id?h.get(y.merged_branch_id):void 0,v=p.get(y.id)||[],w=f.get(y.id)||[];return{...y,branch:x,mergedBranch:b,analyses:v,entities:w}}).map(kt)}catch(d){return fe("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:s}),[]}}async function Et({projectId:e,branchId:t,fileIds:r,filePaths:a,names:o,shas:s}){if(r&&r.length==0||a&&a.length==0||o&&o.length==0||s&&s.length==0)return[];if(s&&s.length>50){const l=[];for(let d=0;d<s.length;d+=50){const m=s.slice(d,d+50),u=await Et({projectId:e,branchId:t,fileIds:r,filePaths:a,names:o,shas:m});u&&l.push(...u)}return l}const i=be();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(!!s,m=>m.where("entities.sha","in",s)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!o,m=>m.where("entities.name","in",o)).$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:s}),null):d.map(Qt)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:s}),null}}function ql(e,t){const{jsonArrayFrom:r}=Pt();let a=e.selectFrom("entity_branches").select(gl);return t&&(a=t(a)),r(a)}async function vo({projectId:e,sha:t}){const r=be();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>ql(o,s=>s.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?Qt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&fe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return fe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Qn=1e3;async function wo({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 wo({projectId:e,filePaths:m,fileIds:r,fileNames:a});u&&l.push(...u)}return l}const o=be(),s=[];let i=0;try{for(;;){let l=o.selectFrom("files").selectAll().where("project_id","=",e).limit(Qn).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||(s.push(...d),d.length<Qn))break;i+=Qn}return s==null?void 0:s.map(Ar)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Gl({id:e,slug:t,withBranches:r,withFiles:a,silent:o}){try{let i=be().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 o||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=kr(l);return a&&(d.files=await wo({projectId:d.id})),r&&(d.branches=await bo({projectId:d.id,includeInactive:!1})),d}catch(s){return o||console.log("CodeYam Error: Error loading project",s),null}}function yn(e,t){const r={...e};for(const a in t){const o=t[a],s=e[a];o!=null&&typeof o=="object"&&!Array.isArray(o)&&s!==void 0&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[a]=yn(s,o):o!==void 0&&(r[a]=o)}return r}async function ct({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:o,updateCallback:s}){try{return await be().transaction().execute(async i=>{var u,h;const l=await i.selectFrom("commits").selectAll().$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!l)return fe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",o)),r=yn(r??{},{currentRun:a});else if(!r&&!s)return d;const m=r?yn(d,r):d;if(o&&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: ${((h=m.historicalRuns)==null?void 0:h.length)||0}`);const p={...m.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),m.historicalRuns=[...m.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${m.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(m.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}s&&await s(m,kt(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",l.id).returningAll().executeTakeFirst()?m:(fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return fe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function Co(e,t,r="analysis"){try{return await be().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return fe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const s=rt(o);return t(s.metadata,s),await a.updateTable("analyses").set({metadata:JSON.stringify(s.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?s.metadata:(fe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return fe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function $t(e,t,r="capture"){try{return await be().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return fe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const s=rt(o);return t(s.status,s),await a.updateTable("analyses").set({status:JSON.stringify(s.status)}).where("id","=",e).returningAll().executeTakeFirst()?s.status:(fe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return fe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Jl({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await be().transaction().execute(async o=>{const s=await o.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!s)return fe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=s.metadata||{};if(!r&&!a)return i;const l=r?yn(i,r):i;a&&await a(l,kr(s));try{return await o.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",s.id).returningAll().executeTakeFirst()?l:(fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(o){return fe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}function Vl(e){const{id:t,projectId:r,analysisId:a,previousVersionId:o,analysis:s,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Vt(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:o}}async function Ql(e){if(e.length===0)return[];const t=be(),r=e.map(Vl);try{return(await t.insertInto("scenarios").values(r).onConflict(_n(r[0],"id",["created_at"])).returningAll().execute()).map(po)}catch(a){return fe("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function Kl(e){const{id:t,commitId:r,branchId:a,...o}=e;return delete o.commit,delete o.branch,{...o,id:t??Vt(),commit_id:r,branch_id:a}}async function Ea(e){if(e.length===0)return[];const t=be(),r=e.map(Kl);try{return(await t.insertInto("commit_branches").values(r).onConflict(_n(r[0],"id",["created_at"])).returningAll().execute()).map(Pr)}catch(a){return fe("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function Zl(e,t){const r=be(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(_n(a,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return fe("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:t}),null}}function Xl(e,t){const{id:r,projectId:a,branchId:o,mergedBranchId:s,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??Vt(),project_id:a??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:o,merged_branch_id:s,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:m}}async function ec({projectId:e,commits:t}){const r=be();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await Zl(i,a[i]);const o=t.map(i=>Xl(i,e));return(await r.insertInto("commits").values(o).onConflict(_n(o[0],"id",["created_at"])).returningAll().execute()).map(kt)}catch(a){return fe("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(o=>o.id).filter(Boolean)}),[]}}const xn=ee.join(Ei.homedir(),".codeyam","secrets.json"),bn=ee.join(process.cwd(),".codeyam","secrets.json");async function pt(){let e={};try{if(Q.existsSync(bn)){const s=await Ie.readFile(bn,"utf8");e=JSON.parse(s)}}catch{console.warn(pn.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(Q.existsSync(xn)){const s=await Ie.readFile(xn,"utf8");e={...JSON.parse(s),...e}}}catch{console.warn(pn.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 o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(t.GROQ_API_KEY=o),t}async function tc(e,t=!0){const r=t?xn:bn,a=ee.dirname(r);await Ie.mkdir(a,{recursive:!0}),await Ie.writeFile(r,JSON.stringify(e,null,2)),await Ie.chmod(r,384)}function nc(e=!0){return e?xn:bn}async function Aa(){const e=await pt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function rc(e){console.log(),console.log(pn.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await Ai({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function ac(e=!0){const t=await Aa();if(t.isValid)return t.secrets;const r=await rc(t.missing),o={...await pt(),...r};await tc(o,e);const s=nc(e);return console.log(pn.green(`✓ Configuration saved to ${s}`)),(await Aa()).secrets}function No(e=process.cwd()){let t=ee.resolve(e);const r=ee.parse(t).root;for(;t!==r;){const o=ee.join(t,".codeyam","config.json");if(Q.existsSync(o))return t;t=ee.dirname(t)}const a=ee.join(r,".codeyam","config.json");return Q.existsSync(a)?r:null}let So=No();function me(){return So}function oc(e){So=e}function Eo(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const sc={"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>`};Eo(sc);const ic={"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>`};Eo(ic);function Yt(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const o=Array.isArray(e)?e:[],s=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?s[i]=Yt(o[i],l,r):s[i]=l}return s}const a={...e};for(const o in t)if(t[o]===null)a[o]=null;else if(Array.isArray(t[o])){const s=Array.isArray(e[o])?e[o]:[];a[o]=[];for(let i=0;i<t[o].length;i++){const l=t[o][i];typeof l=="object"&&l!==null?a[o][i]=Yt(s[i],l,r):a[o][i]=l}}else typeof t[o]=="object"&&t[o]!==null?a[o]=Yt(a[o]??{},t[o],r):a[o]=t[o];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function lc({projectId:e,commit:t,branch:r}){var l,d,m,u,h,p,f;let a;const o={commitId:t.id,branchId:r.id,active:!0},s=await Bl({projectId:e,commitId:t.id,includeBranches:!0});if(s&&s.length>0){a=(l=s.sort((y,x)=>{var b,v,w,C;return(((v=(b=y.branch.metadata)==null?void 0:b.permanent)==null?void 0:v.order)??999)-(((C=(w=x.branch.metadata)==null?void 0:w.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:l.branch,a&&((m=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:m.order)!==void 0&&(((h=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:h.order)<=((f=(p=a.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?a=r:o.active=!1);const g=s.filter(y=>y.active&&y.branch.id!==a.id||!y.active&&y.branch.id===a.id);g.length>0&&await Ea(g.map(y=>({...y,active:y.branchId===a.id})))}(s==null?void 0:s.find(g=>g.branchId===o.branchId))||await Ea([o])}function ft(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=me();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return pe.join(e,".codeyam","db.sqlite3")}async function $e(){const e=await ac();process.env.SQLITE_PATH=ft(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Fe(e){await $e();const t=await Gl({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await bo({projectId:t.id,names:["_local"]}),a=r==null?void 0:r[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:a}}async function cc(e,t,r){await $e();const a=me(),o=jl(`${e.slug}-local-${Date.now()}-${Math.random()}`),s=r.map(d=>{let m="";if(a)try{if(m=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const h=u.split(`
|
|
30
|
+
`);m=`@@ -0,0 +1,${h.length} @@
|
|
31
|
+
${h.map(p=>`+${p}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:m}}),i={sha:o,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${o}`,htmlUrl:`local://codeyam/${e.slug}/${o}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:s,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await ec({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await lc({projectId:e.id,commit:l[0],branch:t}),l[0]}async function Zt(){await $e();const e=await Et({});if(!e||e.length===0)return[];const t=e.filter(l=>{var d;return!((d=l.metadata)!=null&&d.isSuperseded)}),r=t.map(l=>l.sha),a=t.map(l=>{var d;return(d=l.metadata)==null?void 0:d.previousVersionWithAnalyses}).filter(l=>!!l),o=[...new Set([...r,...a])],s=await ut({entityShas:o}),i=new Map;if(s)for(const l of s)i.has(l.entitySha)||i.set(l.entitySha,[]),i.get(l.entitySha).push(l);return t.map(l=>{var u;const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const m=(u=l.metadata)==null?void 0:u.previousVersionWithAnalyses;if(m){const h=i.get(m)||[];return{...l,analyses:h}}return{...l,analyses:[]}})}async function Tn(e,t){await $e();const r=await ut({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await vo({projectId:r[0].projectId,sha:e});if(a)for(const o of r)o.entity=a}return r||[]}async function _r(e){if(await $e(),e.name&&e.projectId){const r=await ut({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(s=>{const i=s.scenarios&&s.scenarios.length>0,l=!e.filePath||s.filePath===e.filePath;return i&&l});if(a.length>0)return a.sort((s,i)=>{const l=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0];const o=r.filter(s=>s.scenarios&&s.scenarios.length>0);if(o.length>0)return o.sort((s,i)=>{const l=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),o[0]}}const t=await ut({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function Ao(e){await $e();const t=await ut({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function At(e){await $e();const t=await Ye();if(!t)return null;const{project:r}=await Fe(t);return await vo({projectId:r.id,sha:e})}async function ko(e){var a,o,s,i,l,d,m,u;await $e();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const p of h){if(!p.filePath||!p.name)continue;const f=await Et({projectId:e.projectId,filePaths:[p.filePath],names:[p.name]});if(f&&f.length>0){const g=f[0],y=await ut({entityShas:[g.sha],limit:1});let x,b,v;if(y&&y.length>0&&y[0].scenarios){const w=y[0],C=w.scenarios||[],E=C.length,S=C.find(k=>{var T,$;return($=(T=k.metadata)==null?void 0:T.screenshotPaths)==null?void 0:$[0]});S&&(x=(s=(o=S.metadata)==null?void 0:o.screenshotPaths)==null?void 0:s[0],b=S.name),v={status:((i=g.metadata)==null?void 0:i.previousVersionWithAnalyses)||w.entitySha!==g.sha?"out_of_date":"up_to_date",scenarioCount:E,timestamp:w.createdAt?new Date(w.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};t.push({...g,screenshotPath:x,scenarioName:b,analysisStatus:v})}}}if((l=e.metadata)!=null&&l.importedBy){const h=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const g=e.metadata.importedBy[p][f];g.shas&&h.push(...g.shas)}if(h.length>0){const p=await Et({projectId:e.projectId,shas:h});if(p)for(const f of p){const g=await ut({entityShas:[f.sha],limit:1});let y,x,b;if(g&&g.length>0&&g[0].scenarios){const v=g[0],w=v.scenarios||[],C=w.length,E=w.find(A=>{var k,T;return(T=(k=A.metadata)==null?void 0:k.screenshotPaths)==null?void 0:T[0]});E&&(y=(m=(d=E.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0],x=E.name),b={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||v.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function Ye(){try{const e=me();if(!e)return null;const t=pe.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Mt(){await $e();try{const e=await Ye();if(!e)return null;const{project:t,branch:r}=await Fe(e),a=await gn({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 Tr(){try{const e=me();if(!e)return null;const t=pe.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Po(e){try{const t=me();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=pe.join(t,e.filePath);return await xe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Mo(e){try{const t=me();if(!t||!e.filePath)return!1;const r=pe.join(t,e.filePath),o=(await xe.stat(r)).mtime.getTime(),s=e.updatedAt||e.createdAt;if(!s)return!1;const i=new Date(s).getTime();return o>i+1e3}catch{return!1}}async function _o(e){if(await $e(),!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 ut({entityShas:r}),o=new Map;if(a)for(const i of a)o.has(i.entitySha)||o.set(i.entitySha,[]),o.get(i.entitySha).push(i);for(const[i,l]of o.entries())l.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const s=t.map(i=>({...i,analyses:o.get(i.sha)||[]}));return s.sort((i,l)=>{var u,h;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((h=l.analyses[0])==null?void 0:h.createdAt)||l.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),s}async function To(e){try{const t=me();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=pe.join(t,".codeyam","config.json"),a=await xe.readFile(r,"utf8"),o=JSON.parse(a),s={...o,...e},i=JSON.stringify(s,null,2);if(await xe.writeFile(r,i,"utf8"),o.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 Jl({projectSlug:o.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const dc=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Zt,getAnalysesForEntity:Tn,getAnalysisForExactEntitySha:Ao,getCurrentCommit:Mt,getEntityBySha:At,getEntityCodeFromFilesystem:Po,getEntityHistory:_o,getLatestAnalysisForEntity:_r,getProjectConfig:Tr,getProjectSlug:Ye,getRelatedEntities:ko,hasFileBeenModifiedSinceEntity:Mo,updateProjectConfig:To},Symbol.toStringTag,{value:"Module"})),Io="secrets.json";function $o(e){return pe.join(e,".codeyam",Io)}function jo(){return pe.join(lr.homedir(),".codeyam",Io)}async function In(e){let t={};try{const r=jo(),a=await xe.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=$o(e),a=await xe.readFile(r,"utf-8"),o=JSON.parse(a);t={...t,...o}}catch{}return t}async function uc(e,t,r=!0){const a=r?jo():$o(e),o=pe.dirname(a);await xe.mkdir(o,{recursive:!0}),await xe.writeFile(a,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}async function mc(e){const t=await In(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)}async function hc({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:o=!1,extraArgs:s=[]}){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(...s);for(const f of r)u.push(`--exclude=${f}`);u.push(d,m);const h=Date.now(),p=kn("rsync",u);p.on("exit",f=>{if(f===0){if(!o){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=>{o||console.log("Error occurred:",f),l(f)})})}const pc=Cr(vr);async function fc(e){return new Promise(t=>setTimeout(t,e))}function gc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ro(e){try{const{stdout:t}=await pc(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
+
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),a=[...r];for(const o of r){const s=await Ro(o);a.push(...s)}return a}catch{return[]}}function ka(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function yc(e,t,r){const a=await Ro(e);for(const o of a.reverse())await ka(o,t,r);await ka(e,t,r)}async function Ht(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function o(s,i){await yc(e,s,t);for(let l=0;l<i;l++)if(await fc(1e3),a+=1e3,!await gc(e))return t(`Process tree ${e} successfully killed with ${s} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${s}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let s=0;s<r;s++)if(await o("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function xc(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Oi(),createdAt:t}}Pi.config({quiet:!0});var Do=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Do||{});class bc extends Mi{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Ti(),{process:a,type:o,name:s,metadata:i,parentId:l}=t,d={id:r,type:o,name:s,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:o,process:s}=a;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(r.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(l=>this.shutdown(l,r))),s.pid)try{await Ht(s.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=s.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(o=>this.shutdown(o.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[o,s]of this.processes.entries()){const{info:i}=s;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const l=s.process.__cleanup;l&&l(),this.processes.delete(o)}}}handleProcessExit(t,r,a){const o=this.processes.get(t);if(!o)return;const{info:s}=o;s.endedAt=Date.now(),s.exitCode=r,s.signal=a,r===0?s.state="completed":a?s.state="killed":s.state="failed",this.emit("processExited",s)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:r.message},this.emit("processExited",o)}}let Kn=null;function vc(){return Kn||(Kn=new bc),Kn}const wc={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Cc({command:e,args:t,workingDir:r,outputOptions:a=wc,processName:o,env:s}){const i={...process.env,...s||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},l=kn(e,t,{cwd:r,env:i});return vc().register({process:l,type:Do.Other,name:o,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const g=pe.join(r,"log.txt");Q.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
|
|
35
|
+
`).map(b=>b.trim()?`[${y}]${g} ${b}`:b).join(`
|
|
36
|
+
`)};l.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&h(y+`
|
|
37
|
+
`),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&h(y+`
|
|
38
|
+
`),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function Nc(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 Sc({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const o=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
+
`);Q.writeFileSync(`${e}/.env`,o);const s=Nc(r);return Cc({command:"node",args:["--enable-source-maps","./dist/project/start.js",...s],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const Ec="/tmp/codeyam/local-dev";function Lo(e){return ee.join(Ec,e)}function Fo(e){return ee.join(Lo(e),"codeyam")}function ot(e){return ee.join(Lo(e),"project")}function $n(e){return ee.join(Fo(e),"log.txt")}const Ac=[".sync-metadata.json","__codeyamMocks__"];async function kc(e,t={}){const{port:r,silent:a=!0}=t,o=ot(e);if(r)try{Me(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${o}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(s=>setTimeout(s,500))}async function Pc(e,t={}){const{killProcesses:r=!0,port:a,silent:o=!0}=t,s=ot(e),i=[],l=[];if(!Q.existsSync(s))return{removed:i,errors:l};r&&await kc(e,{port:a,silent:o});for(const d of Ac){const m=ee.join(s,d);if(Q.existsSync(m))try{(await Ie.stat(m)).isDirectory()?await Ie.rm(m,{recursive:!0,force:!0}):await Ie.unlink(m),i.push(d)}catch(u){l.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const Mc=ee.dirname(wr(import.meta.url));function _c(e){let t=e;for(;t!==ee.dirname(t);){const r=ee.join(t,"package.json");if(Q.existsSync(r))try{if(JSON.parse(Q.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=ee.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Ir(){const e=_c(Mc);return ee.join(e,"analyzer-template")}function jt(e){return Fo(e)}async function Pa(e){const t=Ir(),r=jt(e);if(!Q.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ie.mkdir(ee.dirname(r),{recursive:!0}),await hc({sourcePath:t,destinationPath:r,silent:!0})}function Rt(e,t,r,a){const o=jt(e);if(!Q.existsSync(o))throw new Error(`Analyzer not found at ${o}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const s=void 0;return Sc({absoluteCodeyamRootPath:o,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:s,stderrToConsole:!1,stderrToFile:!0,stderrCallback:s}})}function Tc(e){const t=Ir(),r=jt(e),a=ee.join(t,".build-info.json"),o=ee.join(r,".build-info.json");if(!Q.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!Q.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!Q.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const s=JSON.parse(Q.readFileSync(a,"utf8")),i=JSON.parse(Q.readFileSync(o,"utf8"));return s.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${s.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(s){return{isFresh:!1,reason:`Error reading build markers: ${s.message}`}}}async function Xt(e,t){const r=jt(e);if(!Q.existsSync(r)){t.update("Creating analyzer..."),await Pa(e);return}const a=Tc(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await Pa(e))}async function $r(e){await Pc(e,{killProcesses:!1})}const Ic=ee.dirname(wr(import.meta.url));function Oo(){let e=Ic;for(;e!==ee.dirname(e);){const t=ee.join(e,"package.json");if(Q.existsSync(t))try{if(JSON.parse(Q.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=ee.dirname(e)}return null}function Ut(e){if(!Q.existsSync(e))return null;try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function $c(){const e=Oo();if(e){const t=[ee.join(e,"src/webserver/build-info.json"),ee.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const a=Ut(r);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}const jr=$c();function Yo(e){const t=Oo();let r=null;if(t){const d=[ee.join(t,"src/webserver/build-info.json"),ee.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const m of d)if(r=Ut(m),r)break}const a=Ir(),o=ee.join(a,".build-info.json"),s=Ut(o);let i=null;if(e){const d=jt(e),m=ee.join(d,".build-info.json");i=Ut(m)}let l=!1;return s&&i?l=s.buildTime>i.buildTime:s&&!i&&e&&(l=!0),{cliVersion:jr,webserverVersion:r,templateVersion:s,cachedAnalyzerVersion:i,isCacheStale:l}}function jn(e){const t=jt(e),r=ee.join(t,".build-info.json"),a=Ut(r);return(a==null?void 0:a.version)??null}function zo(){const e=me();return e?ee.join(e,".codeyam","server.json"):null}function Bo(){const e=zo();if(!e||!Q.existsSync(e))return null;try{const t=Q.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function jc(){const e=zo();if(e)try{Q.unlinkSync(e)}catch{}}const Rc="/assets/globals-DMUaGAqV.css";function Dc({text:e,subtext:t,linkText:r,linkTo:a}){const[o,s]=M(!1);return o?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(ae,{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:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Lc({serverVersion:e}){const[t,r]=M("stale"),[a,o]=M(null),s=async()=>{r("restarting"),o(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const d=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<d?setTimeout(()=>void u(),m):(o("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){o(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),c("div",{className:"flex-1",children:[t==="stale"&&c(ce,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),c("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),a&&n("p",{className:"text-xs text-red-600 mt-1",children:a})]}),t==="restarting"&&c(ce,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&c(ce,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void s(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&c("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[c("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function vn(e){return ee.join(e,".codeyam","queue.json")}function zt(e){const t=vn(e);if(!Q.existsSync(t))return{paused:!1,jobs:[]};try{const r=Q.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Fc(e,t){const r=vn(e),a=ee.dirname(r);Q.existsSync(a)||Q.mkdirSync(a,{recursive:!0});try{Q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}async function Oc(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Yc(e,t,r);else if(e.type==="baseline")await zc(e,t,r);else if(e.type==="recapture")await Bc(e,t,r);else if(e.type==="capture-only")await Uc(e,t,r);else if(e.type==="debug-setup")await Wc(e,t,r);else if(e.type==="interactive-start")await Hc(e,t,r);else if(e.type==="interactive-stop")await qc(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(a){throw console.error(`[Queue] Job ${e.id} failed:`,a),a}}async function Yc(e,t,r){var y,x,b,v;const{projectSlug:a,commitSha:o,entityShas:s}=e;if(!o)throw new Error("Analysis job missing commitSha");const i=s||[],{project:l}=await Fe(a);await $r(a),await Xt(a,{update:w=>console.log(`[Queue] ${w}`)});const d=jn(a),m={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{}},u=(x=(y=l.metadata)==null?void 0:y.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const h=e.onlyDataStructure,p={packageManager:((b=l.metadata)==null?void 0:b.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:u.framework,...h?{}:{orchestrateCapture:"local-sequential"}},f=Rt(a,m,p),g=w=>{try{return process.kill(w,0),!0}catch{return!1}};await ct({commitSha:o,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((v=e.filePaths)==null?void 0:v.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const w=new Promise((C,E)=>setTimeout(()=>E(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,w]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await ct({commitSha:o,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{g(f.process.pid)&&await Ht(f.process.pid,()=>{})}catch{}}}catch(w){if(console.error(`[Queue] Analysis job ${e.id} failed:`,w),f.process.pid&&g(f.process.pid))try{await Ht(f.process.pid,()=>{})}catch{}try{await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:w instanceof Error?w.message:String(w)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw w}}async function zc(e,t,r){var p,f,g;const{projectSlug:a,commitSha:o}=e;if(!o)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:s}=await Fe(a);await $r(a),await Xt(a,{update:y=>console.log(`[Queue] ${y}`)});const i=jn(a),l={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=s.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const m={packageManager:((g=s.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=Rt(a,l,m),h=y=>{try{return process.kill(y,0),!0}catch{return!1}};await ct({commitSha:o,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((x,b)=>setTimeout(()=>b(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{h(u.process.pid)&&await Ht(u.process.pid,()=>{})}catch{}}}async function Bc(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Recapture job missing analysisId");const l=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:b}=await import("./index-967OuJoF.js"),v=b(),w=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};w!=null&&w.metadata&&(typeof w.metadata=="string"?C=JSON.parse(w.metadata):C=w.metadata),C.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await $t(o,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!s||v.name===s)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:d}=await Fe(a);await Xt(a,{update:b=>console.log(`[Queue] ${b}`)});const m=jn(a),u={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,framework:((x=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??Kt.Next,orchestrateCapture:"local-sequential"},p=Rt(a,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Uc(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Capture-only job missing analysisId");const l=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:b}=await import("./index-967OuJoF.js"),v=b(),w=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};w!=null&&w.metadata&&(typeof w.metadata=="string"?C=JSON.parse(w.metadata):C=w.metadata),C.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await $t(o,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!s||v.name===s)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:d}=await Fe(a);await Xt(a,{update:b=>console.log(`[Queue] ${b}`)});const m=jn(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,fast:!0,framework:((x=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??Kt.Next,orchestrateCapture:"local-sequential"},p=Rt(a,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Wc(e,t,r){var p,f,g,y;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Debug setup job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await Fe(a);await $r(a),await Xt(a,{update:x=>console.log(`[Queue] ${x}`)});const d={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,PREP_ONLY:"true"};s&&(d.SCENARIO_IDS=s);const m={packageManager:((p=l.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((y=(g=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||Kt.Next},h=await Rt(a,d,m).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function Hc(e,t,r){var h,p,f,g;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Interactive start job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await Fe(a),d={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,INTERACTIVE_MODE:"true"};s&&(d.SCENARIO_IDS=s);const m={packageManager:((h=l.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((g=(f=(p=l.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:g.framework)||Kt.Next};await $t(o,y=>{y.readyToBeCaptured=!0});const u=Rt(a,d,m);await Co(o,y=>{y.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${o}, PID: ${u.process.pid}`)}async function qc(e,t,r){var d;const{projectSlug:a,analysisId:o}=e;if(!o)throw new Error("Interactive stop job missing analysisId");const s=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${o} not found`);const i=(d=s.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${o}`);return}const l=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${o}, killing PID: ${l}`);try{try{process.kill(l,0)}catch{console.log(`[Queue] Process ${l} already exited`);return}await Ht(l,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${l}`)}catch(m){throw console.error(`[Queue] Failed to kill process ${l}:`,m),m}finally{await Co(o,m=>{m.interactiveMode=null})}}class Gc{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=zt(this.projectRoot),this.state.jobs.length>0?(this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0),this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||Vt(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const o=new Promise((s,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):s()})});return this.state.paused||this.processNext().catch(s=>{console.error("[Queue] ERROR in processNext():",s)}),{jobId:r,completion:o}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(o=>o.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const o=this.completionCallbacks.get(t);o&&(setImmediate(()=>o(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const o=r==="up"?a-1:a+1;if(o<0||o>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const s=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[o],this.state.jobs[o]=s,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${o})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const 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 Oc(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Fc(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Jc{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=vn(this.projectRoot);if(!Q.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=vn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=Q.watch(r,(a,o)=>{o==="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=Q.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Vc{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=zt(r)}start(){this.cachedState=zt(this.projectRoot),console.log(`[ProxyQueue] Connected to background server at ${this.serverInfo.url}`),console.log(`[ProxyQueue] Current queue has ${this.cachedState.jobs.length} jobs`),this.fileWatcher=new Jc(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const o=new Promise((i,l)=>{r=i,a=l}),s=`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:s,completion:o}}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=zt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=zt(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 Qc(e){const t=ee.join(e,".codeyam","server.json");if(!Q.existsSync(t))return null;try{const r=Q.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Kc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Zc(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 Xc(e){const t=Qc(e);return!t||!Kc(t.pid)||!await Zc(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class ed extends _i{constructor(){super();an(this,"watcher",null);an(this,"dbPath",null);an(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=ft();const{default:r}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",o=>{const s=Date.now(),i=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${o}`),console.log(`[dbNotifier] Timestamp: ${i} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:s})}).on("error",o=>{console.error("Database watcher error:",o),this.emit("error",o)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const a=Date.now(),o=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${o} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const cr=new ed;let vt=null,Bt=null;async function td(){if(!vt){if(Bt){await Bt;return}Bt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||No()||process.cwd();oc(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await Xc(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Vc(t,e,()=>{cr.notifyChange("unknown")});await r.start(),vt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Gc(e,cr);await r.start(),vt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Bt}}async function st(){return vt||await td(),vt}function nd(){return vt||(Bt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const rd=()=>[{rel:"stylesheet",href:Rc},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function ad({request:e,context:t}){var r,a,o,s,i,l,d;try{const m=me()||process.cwd(),[u,h,p]=await Promise.all([Mt(),Ye(),In(m)]);if(!h)throw new Error("Project slug not found");const f=t.analysisQueue||nd(),g=f==null?void 0:f.getState(),y=async R=>{if(!R||R.length===0)return[];const F=Math.min(Math.max(R.length*2e3,1e4),6e4),L=new Promise(j=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${F}ms for ${R.length} entities`),j([])},F)),G=Promise.all(R.map(j=>At(j))).then(j=>j.filter(N=>N!==null));return Promise.race([G,L])},x=await Promise.all(((g==null?void 0:g.jobs)||[]).map(async R=>{var L;const F=await y(R.entityShas||[]);return F.length===0&&((L=R.entityShas)!=null&&L.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",R.id),{...R,entities:F}}));let b=null;if(g!=null&&g.currentlyExecuting){const R=g.currentlyExecuting,F=await y(R.entityShas||[]);F.length===0&&((r=R.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",R.id),b={...R,entities:F}}const v=b?x.filter(R=>R.id!==b.id):x;let w=((o=(a=u==null?void 0:u.metadata)==null?void 0:a.currentRun)==null?void 0:o.currentEntityShas)||[];if(w.length===0){const R=((s=u==null?void 0:u.metadata)==null?void 0:s.historicalRuns)||[];if(R.length>0){const L=[...R].sort((G,j)=>{const N=G.archivedAt||G.createdAt||"";return(j.archivedAt||j.createdAt||"").localeCompare(N)})[0];if(L){const G=L.analysisCompletedAt||L.createdAt;if(G){const j=new Date(G).getTime(),z=Date.now()-1440*60*1e3;j>z&&(w=L.currentEntityShas||[])}}}}const C=await y(w),E=[];p.ANTHROPIC_API_KEY&&E.push("ANTHROPIC_API_KEY"),p.GROQ_API_KEY&&E.push("GROQ_API_KEY"),p.OPENAI_API_KEY&&E.push("OPENAI_API_KEY"),p.OPENROUTER_API_KEY&&E.push("OPENROUTER_API_KEY");const{project:S,branch:A}=await Fe(h),k=await gn({projectId:S.id,branchId:A.id,limit:20}),T=[];for(const R of k){const F=((i=R.metadata)==null?void 0:i.historicalRuns)||[];for(const L of F){const G=L.currentEntityShas||[];if(G.length>0){const j=await y(G);T.push({...L,entities:j})}else T.push(L)}}const $=T.sort((R,F)=>{const L=R.archivedAt||R.analysisCompletedAt||R.createdAt||"";return(F.archivedAt||F.analysisCompletedAt||F.createdAt||"").localeCompare(L)}),D=new Set(((l=b==null?void 0:b.entities)==null?void 0:l.map(R=>R.sha))||[]),P=$.filter(R=>!(R.currentEntityShas||[]).some(L=>D.has(L))),_=Bo(),I=(_==null?void 0:_.cliVersion)??"unknown",O=I!=="unknown"&&I!==jr,V={currentRun:(d=u==null?void 0:u.metadata)==null?void 0:d.currentRun,projectSlug:h,currentEntities:C,availableAPIKeys:E,queuedJobCount:v.length,queueJobs:v,currentlyExecuting:b,historicalRuns:P,isServerOutOfDate:O,serverVersion:I};return U(V)}catch(m){return console.error("Failed to load root data:",m),U({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown"})}}function od(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:d,serverVersion:m}=We(),{toasts:u,closeToast:h}=Er(),p=nt(),f=Se(p),g=En();ne(()=>{f.current=p},[p]);const y=g.pathname.startsWith("/entity/")&&g.pathname.includes("/edit/")||g.pathname.startsWith("/dev/"),x=g.pathname.includes("/fullscreen");return ne(()=>{const b=new EventSource("/api/events");let v=null,w=0;const C=2e3;return b.addEventListener("message",E=>{const S=JSON.parse(E.data);if(S.type==="queue")f.current.revalidate(),w=Date.now();else if(S.type==="db-change"||S.type==="unknown"){const A=Date.now(),k=A-w;k<C?(v&&clearTimeout(v),v=setTimeout(()=>{f.current.revalidate(),w=Date.now(),v=null},C-k)):(f.current.revalidate(),w=A)}}),b.addEventListener("error",E=>{console.error("SSE connection error:",E)}),()=>{v&&clearTimeout(v),b.close()}},[]),c(ce,{children:[c("div",{className:`min-h-screen ${y?"":"grid"} bg-cygray-10`,style:y?void 0:{gridTemplateColumns:"65px minmax(900px, 1fr)"},children:[!y&&n(Qi,{}),c("div",{className:"max-h-screen overflow-auto bg-cygray-10",children:[d&&n(Lc,{serverVersion:m}),a.length===0&&n(Dc,{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(Is,{})]})]}),n(Xi,{toasts:u,onClose:h}),!x&&n(el,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:l})]})}const sd=Oe(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(Ps,{}),n(Ms,{})]}),c("body",{children:[n(Ki,{children:n(Ji,{children:n(od,{})})}),n(_s,{}),n(Ts,{})]})]})}),id=Object.freeze(Object.defineProperty({__proto__:null,default:sd,links:rd,loader:ad},Symbol.toStringTag,{value:"Module"}));function Ma(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function en({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:o=!0,refreshTrigger:s=0}){const i=Ee(),[l,d]=M(null),[m,u]=M(!1),[h,p]=M(!1),[f,g]=M(!1),y=Se(!1),x=Se(null),b=Se(null),[v,w]=M(0),[C,E]=M(0),S=Se(null),A=Se(!1),{interactiveUrl:k,resetLogs:T}=ht(a,o),$=Se(t),D=Se(s);ne(()=>{D.current!==s&&(D.current=s,l&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),w(0),E(_=>_+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null)))},[s,l]),ne(()=>{if($.current!==t&&($.current=t,x.current&&b.current&&r)){const _=Ma(b.current),I=Ma(r),O=x.current.replace(_,I);d(O),p(!0),g(!1),w(0),E(V=>V+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r]),ne(()=>{if(k){const _=k+"?width=600px";x.current=_,r&&(b.current=r),d(_),u(!1),p(!0)}},[k]),ne(()=>{const _=I=>{I.data.type==="codeyam-resize"&&(A.current||(A.current=!0,S.current&&(clearTimeout(S.current),S.current=null),w(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",_),()=>window.removeEventListener("message",_)},[]);const P=()=>{A.current=!1,S.current&&clearTimeout(S.current);const _=500*Math.pow(2,v);S.current=setTimeout(()=>{A.current||(v<2?(w(I=>I+1),E(I=>I+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},_)};return ne(()=>{o&&!y.current&&t&&e&&(y.current=!0,u(!0),g(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(I){console.error("[useInteractiveMode] Failed to clear log file:",I)}T(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,T,a]),ne(()=>{const _=e,I=()=>{if(y.current&&_){const V=new URLSearchParams({action:"stop",analysisId:_});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const R=navigator.sendBeacon("/api/interactive-mode",V);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:V,keepalive:!0}).catch(F=>console.error("Failed to stop interactive mode:",F)))}},O=()=>{I()};return window.addEventListener("beforeunload",O),()=>{window.removeEventListener("beforeunload",O),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:_}),I()}},[e]),{interactiveServerUrl:l,isStarting:m,isLoading:h,showIframe:f,iframeKey:C,onIframeLoad:P}}const sn=10,ld=1024;function Uo({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:o,hideLabel:s=!1,lightMode:i=!1}){const[l,d]=M(null),m=Se(null),u=oe(()=>[...a].sort((v,w)=>v.width-w.width),[a]),{fittingPresets:h,overflowPresets:p}=oe(()=>{const v=[],w=[];for(const C of u)C.width<=ld?v.push(C):w.push(C);return w.sort((C,E)=>E.width-C.width),{fittingPresets:v,overflowPresets:w}},[u]),f=se(v=>{if(!m.current)return null;const w=m.current.getBoundingClientRect(),C=v-w.left,E=w.width,S=E/2,k=(h.length>0?h[h.length-1].width:0)/2,T=S-k,$=S+k,D=p.length>0?(p.length-1)*sn:0;if(p.length>0){if(C<T){if(C<=D){const _=Math.min(Math.floor(C/sn),p.length-1);return p[_]}return p[p.length-1]}if(C>$){const _=E-C;if(_<=D){const I=Math.min(Math.floor(_/sn),p.length-1);return p[I]}return p[p.length-1]}}const P=Math.abs(C-S);for(let _=h.length-1;_>=0;_--){const I=h[_],O=h[_-1],V=I.width/2,R=O?O.width/2:0;if(P<=V&&P>=R)return I}return h[0]||p[p.length-1]||null},[h,p]),g=se(v=>{const w=f(v.clientX);d(w),o==null||o(w)},[f,o]),y=se(()=>{d(null),o==null||o(null)},[o]),x=se(v=>{const w=f(v.clientX);w&&r(w)},[f,r]),b=l||{name:t,width:e};return c("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:g,onMouseLeave:y,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(v=>{const w=v.width===e,C=(l==null?void 0:l.name)===v.name,E=v.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((v,w)=>{const C=w*sn,E=v.width===e,S=(l==null?void 0:l.name)===v.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),!s&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function Wo({width:e,height:t,onSave:r,onCancel:a}){const[o,s]=M(""),[i,l]=M(""),d=()=>{const u=o.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 cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:o,onChange:u=>{s(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&o.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&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 cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!o.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function Ho(e){const[t,r]=M([]),a=e?`codeyam-custom-sizes-${e}`:null;ne(()=>{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 o=se(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]),s=se((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],o(f),f})},[o]),i=se(l=>{r(d=>{const m=d.filter(u=>u.name!==l);return o(m),m})},[o]);return{customSizes:t,addCustomSize:s,removeCustomSize:i}}function wn(){return c("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
40
|
+
.loader {
|
|
41
|
+
width: 48px;
|
|
42
|
+
height: 48px;
|
|
43
|
+
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
44
|
+
border-radius: 50%;
|
|
45
|
+
display: inline-block;
|
|
46
|
+
position: relative;
|
|
47
|
+
box-sizing: border-box;
|
|
48
|
+
animation: rotation 1s linear infinite;
|
|
49
|
+
}
|
|
50
|
+
.loader::after {
|
|
51
|
+
content: '';
|
|
52
|
+
box-sizing: border-box;
|
|
53
|
+
position: absolute;
|
|
54
|
+
left: 50%;
|
|
55
|
+
top: 50%;
|
|
56
|
+
transform: translate(-50%, -50%);
|
|
57
|
+
width: 56px;
|
|
58
|
+
height: 56px;
|
|
59
|
+
border-radius: 50%;
|
|
60
|
+
border: 3px solid;
|
|
61
|
+
border-color: #005c75 transparent;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
@keyframes rotation {
|
|
65
|
+
0% {
|
|
66
|
+
transform: rotate(0deg);
|
|
67
|
+
}
|
|
68
|
+
100% {
|
|
69
|
+
transform: rotate(360deg);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`})]})}const _a=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],cd=80;function Cn(){const[e,t]=M(0);return ne(()=>{const r=setInterval(()=>{t(a=>(a+1)%_a.length)},cd);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:_a[e]})}async function dd({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw U("Invalid parameters",{status:400});const a=await At(t);if(!a)throw U("Entity not found",{status:404});const o=await _r(a),s=((l=o==null?void 0:o.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!s)throw U("Scenario not found",{status:404});const i=await Ye();return U({entity:a,scenario:s,analysis:o,projectSlug:i})}const Zn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],ud=Oe(function(){const{entity:t,scenario:r,analysis:a,projectSlug:o}=We(),s=It(),[i]=Jt(),[l,d]=M(null),[m,u]=M(1440),[h,p]=M({name:"Desktop",width:1440,height:900}),[f,g]=M(!1),[y,x]=M(null),{customSizes:b,addCustomSize:v}=Ho(o),w=oe(()=>[...Zn,...b],[b]),{interactiveServerUrl:C,isStarting:E,isLoading:S,showIframe:A,iframeKey:k,onIframeLoad:T}=en({analysisId:a==null?void 0:a.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),{lastLine:$}=ht(o,E||S),D=()=>{s(`/entity/${t.sha}`)},P=(W,H)=>{u(W);const re=w.find(Y=>Y.width===W&&Y.height===H);d(re||null),p({name:(re==null?void 0:re.name)||"Custom",width:W,height:H})},_=W=>{d(W),u(W.width),p({name:W.name,width:W.width,height:W.height})},I=W=>{v(W,h.width,h.height??900),g(!1),p(H=>({...H,name:W}))},O=((a==null?void 0:a.scenarios)||[]).filter(W=>{var H;return!((H=W.metadata)!=null&&H.sameAsDefault)}),V=O.findIndex(W=>W.id===(r==null?void 0:r.id)),R=V+1,F=O.length,L=V>0,G=V<O.length-1,j=()=>{if(L){const W=O[V-1],H=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);s(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${H}`)}},N=()=>{if(G){const W=O[V+1],H=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);s(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${H}`)}},z=E||S||!A;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:co,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:j,disabled:!L,className:`${L?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[R,"/",F]}),n("button",{onClick:N,disabled:!G,className:`${G?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:D,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Zn[Zn.length-1].width}px`,width:"100%"},children:n(Uo,{currentViewportWidth:m,currentPresetName:h.name,onDevicePresetClick:_,devicePresets:w,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(y==null?void 0:y.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:h.name,onChange:W=>{const H=w.find(re=>re.name===W.target.value);H&&_(H)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[w.map(W=>n("option",{value:W.name,children:W.name},W.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:W=>{const H=parseInt(W.target.value,10);!isNaN(H)&&H>0&&P(H,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
73
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
74
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
76
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
77
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?c("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[z&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(wn,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),$&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Cn,{}),$]})]})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:T,style:{opacity:A?1:0}},k)]}):c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(wn,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),$&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Cn,{}),$]})]})]})}),f&&n(Wo,{width:h.width,height:h.height??900,onSave:I,onCancel:()=>g(!1)})]})}),md=Object.freeze(Object.defineProperty({__proto__:null,default:ud,loader:dd},Symbol.toStringTag,{value:"Module"})),qo=gr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Rr=()=>{const e=An(qo);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Rn=({children:e})=>{const[t,r]=M({height:720,width:1200}),[a,o]=M(1),[s,i]=M(1200),l=Se(null),d=se(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),m=se(h=>{o(h)},[]),u=se(h=>{i(h)},[]);return n(qo.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:m,maxWidth:s,updateMaxWidth:u},children:e})},hd=typeof window<"u";function pd(){const[e,t]=M(null);return ne(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const fd=1200,gd=720,Ta=30,yd=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:o=900,onDataOverride:s,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const m=pd(),[u,h]=M(!1),[p,f]=M(!1),[g,y]=M(fd),[x,b]=M(gd),[v,w]=M(null),[C,E]=M(null),{dimensions:S,updateDimensions:A,iframeRef:k,updateScale:T,updateMaxWidth:$}=Rr(),D=oe(()=>Math.min(1,g/S.width),[g,S.width]),P=C!==null?C:D;ne(()=>{u||(T(P),l==null||l(P))},[P,T,l,u]),ne(()=>{$(g)},[g,$]);const _=se(()=>{h(!0),E(D)},[D]),I=se(()=>{h(!1),E(null)},[]),O=se((G,j)=>{const N=C!==null?C:1,z=Math.round(j.size.width/N);A({width:z}),d==null||d(z,S.height)},[A,C,d,S.height]),V=se(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ne(()=>{const G=j=>{if(j.data.type==="codeyam-resize"){if(t&&j.data.name!==t||S.height===j.data.height||j.data.height===0)return;A({height:j.data.height})}};return window.addEventListener("message",G),()=>{window.removeEventListener("message",G)}},[k,t,a,S,A]),ne(()=>{p&&s&&s(k.current)},[p,s,k]),ne(()=>{if(!t)return;const G=setInterval(()=>{var j,N;(N=(j=k==null?void 0:k.current)==null?void 0:j.contentWindow)==null||N.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(G)},[t,k]),ne(()=>{const G=()=>{const j=document.getElementById("scenario-container");if(!j)return;const N=j.getBoundingClientRect(),z=j.clientWidth-Ta*2,W=window.innerHeight-N.top-Ta*2,H=Math.max(W,400),re=window.innerHeight-N.top;y(z),b(H),w(re)};return G(),window.addEventListener("resize",G),()=>window.removeEventListener("resize",G)},[]),ne(()=>{A({width:a,height:o})},[a,o,A]);const R=oe(()=>S.width*P,[S.width,P]),F=oe(()=>{const G=S.height,j=G*P;return G&&G!==720&&G!==900&&j<x?j:x},[S.height,x,P]),L=se(()=>{window.history.back()},[]);return!hd||!m?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
78
|
+
.react-resizable-handle-e {
|
|
79
|
+
display: flex !important;
|
|
80
|
+
align-items: center !important;
|
|
81
|
+
justify-content: center !important;
|
|
82
|
+
width: 6px !important;
|
|
83
|
+
height: 48px !important;
|
|
84
|
+
right: -8px !important;
|
|
85
|
+
top: 50% !important;
|
|
86
|
+
transform: translateY(-50%) !important;
|
|
87
|
+
cursor: ew-resize !important;
|
|
88
|
+
background: #d1d5db !important;
|
|
89
|
+
border-radius: 3px !important;
|
|
90
|
+
opacity: 0 !important;
|
|
91
|
+
transition: all 0.2s ease !important;
|
|
92
|
+
}
|
|
93
|
+
.react-resizable-handle-e:hover {
|
|
94
|
+
opacity: 0.8 !important;
|
|
95
|
+
background: #9ca3af !important;
|
|
96
|
+
}
|
|
97
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
98
|
+
opacity: 0.4 !important;
|
|
99
|
+
}
|
|
100
|
+
`}),n(m,{width:R,height:F,minConstraints:[300,200],maxConstraints:[g,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:_,onResizeStop:I,onResize:O,children:n("div",{className:"overflow-auto",style:{width:`${R}px`,height:`${F}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${P})`,transformOrigin:"top left"},children:r?n("iframe",{ref:k,className:"w-full h-full rounded-lg",src:r,onLoad:V,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:L,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function xd({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:o,onSizeChange:s,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[m,u]=M(!1),[h,p]=M(String(r)),[f,g]=M(String(a)),[y,x]=M(!1),[b,v]=M(!1),w=Se(null);ne(()=>{y||p(String(r))},[r,y]),ne(()=>{b||g(String(a))},[a,b]),ne(()=>{const P=_=>{w.current&&!w.current.contains(_.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const C=oe(()=>{const P=e.find(I=>I.width===r&&I.height===a);if(P)return P.name;const _=t.find(I=>I.width===r&&I.height===a);return _?_.name:"Custom"},[e,t,r,a]),E=C==="Custom",S=P=>{s(P.width,P.height),u(!1)},A=P=>{const _=P.target.value;p(_);const I=parseInt(_,10);!isNaN(I)&&I>0&&s(I,a)},k=P=>{const _=P.target.value;g(_);const I=parseInt(_,10);!isNaN(I)&&I>0&&s(r,I)},T=()=>{x(!1);const P=parseInt(h,10);(isNaN(P)||P<=0)&&p(String(r))},$=()=>{v(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&g(String(a))},D=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:w,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:C}),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(ce,{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:()=>S(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 ${C===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(ce,{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,_)=>P.width-_.width).map(P=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>S(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:_=>{_.stopPropagation(),C===P.name&&e.length>0&&s(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:A,onFocus:()=>x(!0),onBlur:T,onKeyDown:D,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:k,onFocus:()=>v(!0),onBlur:$,onKeyDown:D,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"})]}),o!==void 0&&o<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),E&&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 Xn(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 dr(e){return e&&(typeof e=="object"||Array.isArray(e))}function bd(e){return Array.isArray(e)?e.length:void 0}function vd(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,o)=>o.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((o,s)=>{const i=dr(t[o]),l=dr(t[s]);return i&&!l?1:!i&&l?-1:o.localeCompare(s)});if(typeof t=="object")return Object.keys(t).sort((o,s)=>o.localeCompare(s))}}function wd({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 Cd({path:e,namedPath:t,isArray:r,count:a,onClick:o}){const s=se(()=>{o&&o(e)},[o,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:s,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 Go=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Go||{});const Nd=({name:e,value:t,options:r,onChange:a})=>{const o=se(s=>{a({target:{name:e,value:s.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:o,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((s,i)=>n("option",{value:s.trim(),children:s.trim()},i))})},Sd=({name:e,value:t,onChange:r})=>{const a=se(o=>{const s=o.target.checked;r({target:{name:e,value:s}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
101
|
+
bg-gray-300 checked:bg-blue-600
|
|
102
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
103
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
104
|
+
checked:after:translate-x-4`})})};function Ed({dataType:e,path:t,value:r,onChange:a}){const o=oe(()=>t[t.length-1],[t]),s=oe(()=>t.join("-"),[t]),i=se(d=>{a(t,d.target.value)},[a,t]),l=se(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:s,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?n(Nd,{name:s,value:r,options:e.split("|"),onChange:i}):e===Go.BOOLEAN?n(Sd,{name:s,value:r??!1,onChange:l}):n("input",{id:s,name:s,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-${s}`)]})}function Ad({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:o}){const[s,i]=M(!1),[l,d]=M(""),m=se(async()=>{if(!o){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Mn),f=await o(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(x,b)=>{const v=Object.assign({},x);return y(x)&&y(b)&&Object.keys(b).forEach(w=>{y(b[w])?w in x?v[w]=g(x[w],b[w]):Object.assign(v,{[w]:b[w]}):Object.assign(v,{[w]:b[w]})}),v},y=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=g(g((p==null?void 0: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,o]),u=se(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:s,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:s?c(ce,{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 kd({namedPath:e,path:t,last:r,onClick:a}){const o=se(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function Pd({dataItem:e,onClick:t}){const r=se(()=>t([]),[t]),a=oe(()=>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((o,s)=>c("div",{className:"flex items-center gap-1",children:[n(kd,{namedPath:e.namedPath.slice(0,s+a+1),path:e.path.slice(0,s+a+1),last:s+a===e.namedPath.length-1,onClick:t}),s+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-${o}-${s+a}`))]})}function Ia({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:o,onAIResult:s,onGenerateData:i,saveFeedback:l}){const d=oe(()=>r.data,[r]),m=oe(()=>vd(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Pd,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(Ad,{analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:i}),m==null?void 0:m.map((u,h)=>{var f;if(dr(d[u])){let g=u;isNaN(Number(u))||(g=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const y=[...r.path,u],x=[...r.namedPath,g];return n(Cd,{path:y,namedPath:x,isArray:Array.isArray(d),count:bd(d[u]),onClick:a},`data-${u}-${h}`)}if(u==="id")return null;const p=[...r.path,u];return n(Ed,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:o},`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==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function $a({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:o=!1}){const[s,i]=M(r),l=[];return a&&l.push("border-t"),o&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!s),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${s?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),s&&n("div",{className:"px-4 py-3",children:t})]})}const Md=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:o,onSave:s,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:m})=>{const u=se((A,k)=>{const T=Object.assign({},A),$=D=>D&&typeof D=="object"&&!Array.isArray(D);return $(A)&&$(k)&&Object.keys(k).forEach(D=>{$(k[D])?D in A?T[D]=u(A[D],k[D]):Object.assign(T,{[D]:k[D]}):Object.assign(T,{[D]:k[D]})}),T},[]),[h,p]=M({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=M(null),y=oe(()=>({...h.data}),[h]),x=oe(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),b=oe(()=>{const A={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(A).reduce((k,T)=>{if(T.includes(".")){const[$,D]=T.split(".");k[$]||(k[$]={}),k[$][D]=A[T]}else k[T]=A[T];return k},{})},[r]),v=se(async A=>{A.preventDefault();const k=A.target.querySelector('input[name="recapture"]'),T=(k==null?void 0:k.value)==="true",$={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:T,dataToSave:$,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify($,null,2).substring(0,1e3));const D=a==null?void 0:a.scenarios.map(P=>!o&&P.name===e.name?{...P,name:h.name,description:h.description,metadata:{...P.metadata,data:$}}:P);o&&D.push({name:h.name,description:h.description,metadata:{data:$,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",D),s&&await s(D,{recapture:T}),i&&i(h.name)},[a,e.name,h,y,o,s,i]),w=se(A=>{p(k=>({...k,[A.target.name]:A.target.value}))},[]),C=se(A=>{g(k=>{if(!k)return null;for(const T of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let $=T;for(const D of k.path)if($=Xn($,D),!$)break;$&&(k.data=$)}return{...k}}),p({name:A.name,description:A.description,data:A.metadata.data})},[]),E=se((A,k)=>{p(T=>{for(const $ of[{"Function Arguments":T.data.argumentsData},{"Retrieved Data":T.data.mockData}]){let D=$;for(const P of A.slice(0,-1))if(D=Xn(D,P),!D)break;if(D){const P=D[A[A.length-1]];g(_=>_?(_.namedPath[_.namedPath.length-1]===P&&(_.namedPath[_.namedPath.length-1]=k.toString()),_.data[A[A.length-1]]=k,{..._}):null),D[A[A.length-1]]=k}}return{...T}})},[]),S=se(A=>{var D,P,_;if(A.length===0){g(null);return}let k=x;const T=[];let $=b;for(const I of A){if(T.push(isNaN(parseInt(I))?I:((D=k[I])==null?void 0:D.name)??((P=k[I])==null?void 0:P.title)??((_=k[I])==null?void 0:_.id)??I),k=Xn(k,I),!k){console.log("Data not found",k,I),g(null);return}Array.isArray($)?$=$[0]:$=$[I]}g({path:A,namedPath:T,data:k,structure:$})},[x,b]);return ne(()=>{const A=k=>{var T;k.data.type==="codeyam-log"&&((T=k.data.data)!=null&&T.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",k.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),ne(()=>{var A;if((A=l==null?void 0:l.current)!=null&&A.contentWindow){const k={arguments:y.argumentsData??[],...y.mockData??{}},T={type:"codeyam-override-data",name:e.name,data:JSON.stringify(k)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:T.type,name:T.name,dataPreview:JSON.stringify(k).substring(0,200)+"...",fullData:k}),l.current.contentWindow.postMessage(T,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:A=>void v(A),children:f?n(Ia,{analysis:a,scenarioName:h.name,dataItem:f,onClick:S,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m}):c(ce,{children:[n($a,{title:"Edit Name and Description",borderT:!0,children:n(wd,{scenarioFormData:h,handleInputChange:w})}),e.metadata.data&&n($a,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Ia,{analysis:a,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:S,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m})})]})})};function Dn({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:o,showIframe:s,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=ht(u??null,a||o);return r?c("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:s?1:0,background:"transparent"},children:n(yd,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:m},i)}),!s&&(a||o)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(wn,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Cn,{}),g]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(wn,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Cn,{}),g]})]})]})})}const _d=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Td({params:e}){var d,m;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 Tn(t,!0),o=a&&a.length>0?a[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const s=(d=o.scenarios)==null?void 0:d.find(u=>u.id===r);if(!s)throw new Response("Scenario not found",{status:404});const i=(m=o.scenarios)==null?void 0:m.find(u=>u.name===Mn),l=await Ye();return U({analysis:o,scenario:s,defaultScenario:i||s,entitySha:t,projectSlug:l})}function Id(){var I,O,V;const e=We(),t=e.analysis,r=e.scenario,a=e.defaultScenario,o=e.entitySha,s=e.projectSlug,i=It(),{iframeRef:l}=Rr(),[d,m]=M(!1),[u,h]=M(null),[p,f]=M(null),[g,y]=M(!1),[x,b]=M(!1),[v,w]=M(null),{interactiveServerUrl:C,isStarting:E,isLoading:S,showIframe:A,iframeKey:k,onIframeLoad:T}=en({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:s,enabled:!0}),$=se(async(R,F)=>{m(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",F),console.log("[EditScenario] Scenarios to save:",R);try{const L={analysis:t,scenarios:R};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:R.length,scenarioNames:R.map(N=>N.name)});const G=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)}),j=await G.json();if(console.log("[EditScenario] API response:",j),!G.ok||!j.success)throw new Error(j.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),F!=null&&F.recapture&&r.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:C}),h("Changes saved. Capturing screenshot...");const N={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",N);const z=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});console.log("[EditScenario] Capture response status:",z.status);const W=await z.json();if(console.log("[EditScenario] Capture response body:",W),!z.ok||!W.success)throw console.error("[EditScenario] Capture failed:",W),new Error(W.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",W),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(F!=null&&F.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const N=new FormData;N.append("analysisId",t.id||""),N.append("scenarioId",r.id||"");const z=await fetch("/api/recapture-scenario",{method:"POST",body:N}),W=await z.json();if(!z.ok||!W.success)throw new Error(W.error||"Failed to trigger recapture");console.log("Recapture queued:",W),f(W.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(L){console.error("Error saving scenarios:",L),h(`Error: ${L instanceof Error?L.message:String(L)}`)}finally{m(!1)}},[t,r.id,C]),D=se(R=>{},[]),P=se(async(R,F)=>{var j;const L=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:R,existingScenarios:t.scenarios,scenariosDataStructure:(j=t.metadata)==null?void 0:j.scenariosDataStructure,editingMockName:r.name,editingMockData:F==null?void 0:F.data})}),G=await L.json();if(!L.ok||!G.success)throw new Error(G.error||"Failed to generate scenario data");return G.data},[t,r.name]),_=se(async()=>{var R;if(!r.id){w("Cannot delete scenario without ID");return}y(!0),w(null);try{const F=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((R=r.metadata)==null?void 0:R.screenshotPaths)||[]})}),L=await F.json();if(!F.ok||!L.success)throw new Error(L.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(F){console.error("[EditScenario] Error deleting scenario:",F),w(F instanceof Error?F.message:"Failed to delete scenario"),b(!1)}finally{y(!1)}},[r.id,(I=r.metadata)==null?void 0:I.screenshotPaths,o,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(ae,{to:`/entity/${o}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(O=t.entity)==null?void 0:O.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(Md,{currentScenario:r,defaultScenario:a,dataStructure:((V=t.metadata)==null?void 0:V.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:$,onNavigate:D,iframeRef:l,onGenerateData:P,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(ae,{to:`/entity/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void _(),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:()=>b(!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:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),v&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:v})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Dn,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:E,isLoading:S,showIframe:A,iframeKey:k,onIframeLoad:T,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const $d=Oe(function(){return n(Rn,{children:n(Id,{})})}),jd=Object.freeze(Object.defineProperty({__proto__:null,default:$d,loader:Td,meta:_d},Symbol.toStringTag,{value:"Module"}));function Rd({executionFlows:e,selections:t,onChange:r,disabled:a=!1}){const o=se(i=>t.some(l=>l.flowId===i),[t]),s=se(i=>{o(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,o]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=o(i.id),d=i.usedInScenarios.length>0;return c("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[c("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>s(i),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&c("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>c("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:m.attributePath})," ",n("span",{className:"text-gray-400",children:m.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:m.value})]},u))})]})]},i.id)})})}function Dr(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;r.forEach(d=>{a.set(d.id,d)});const o=[];t.forEach(d=>{var u;const m=((u=d.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(h=>{const p=a.get(h);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),o.push({scenario:d,coveredFlowIds:m})});const s=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,l=s>0?i/s*100:0;return{executionFlows:r,totalFlows:s,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:o}}function Dd(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Ld=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Fd({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Tn(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(i=a.scenarios)==null?void 0:i.find(l=>l.name===Mn);if(!o)throw new Response("Default scenario not found",{status:404});const s=await Ye();return U({analysis:a,defaultScenario:o,entity:a.entity,entitySha:t,projectSlug:s})}function Od(){var L;const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:o}=We(),s=It(),{iframeRef:i}=Rr(),[l,d]=M(""),[m,u]=M(400),[h,p]=M(!1),[f,g]=M(!1),[y,x]=M(!1),[b,v]=M(null),[w,C]=M(null),[E,S]=M([]),A=oe(()=>{var j;return!((j=e==null?void 0:e.metadata)!=null&&j.executionFlows)||!(e!=null&&e.scenarios)?[]:Dr(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:k,isStarting:T,isLoading:$,showIframe:D,iframeKey:P,onIframeLoad:_}=en({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:o,enabled:!0}),I=se(async()=>{var G,j,N,z;if(!l.trim()&&E.length===0){v("Please describe how you want to change the scenario or select execution flows");return}g(!0),v(null),C("Generating scenario with AI...");try{const W=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(G=e.metadata)==null?void 0:G.scenariosDataStructure,flowSelections:E.length>0?E:void 0})}),H=await W.json();if(!W.ok||!H.success)throw new Error(H.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",H.data);const re=H.data;if(!re.name||!re.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),x(!0);const J={name:re.name,description:re.description||l,metadata:{data:re.data,interactiveExamplePath:(j=t.metadata)==null?void 0:j.interactiveExamplePath}},Y=[...e.scenarios||[],J],q=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:Y})}),K=await q.json();if(!q.ok||!K.success)throw new Error(K.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",K);const B=(z=(N=K.analysis)==null?void 0:N.scenarios)==null?void 0:z.find(Z=>Z.name===re.name);if(!(B!=null&&B.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void s(`/entity/${a}`),1e3);return}if(k){C("Capturing screenshot...");const Z=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:k,scenarioId:B.id,projectId:e.projectId,viewportWidth:1440})}),de=await Z.json();!Z.ok||!de.success?(console.error("[CreateScenario] Capture failed:",de),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{s(`/entity/${a}/scenarios/${B.id}`)},1e3)}catch(W){console.error("[CreateScenario] Error:",W),v(W instanceof Error?W.message:String(W)),C(null)}finally{g(!1),x(!1)}},[l,E,e,t,a,k,s]),O=f||y,V=se(()=>{p(!0)},[]),R=se(G=>{if(!h)return;const j=G.clientX;j>=250&&j<=600&&u(j)},[h]),F=se(()=>{p(!1)},[]);return ne(()=>(h?(document.addEventListener("mousemove",R),document.addEventListener("mouseup",F)):(document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",F)),()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",F)}),[h,R,F]),c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void s(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),c("div",{className:"flex items-end gap-8 shrink-0",children:[n(ae,{to:`/entity/${a}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:c("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((L=e==null?void 0:e.scenarios)==null?void 0:L.length)||0})]})}),n(ae,{to:`/entity/${a}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(ae,{to:`/entity/${a}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(ae,{to:`/entity/${a}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(ae,{to:`/entity/${a}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[c("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${m}px`},children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),A.length>0&&c("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[c("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",E.length>0&&c("span",{className:"text-blue-600",children:["(",E.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Rd,{executionFlows:A,selections:E,onChange:S,disabled:O})})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:G=>d(G.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:O})]}),c("div",{className:"space-y-2",children:[n("button",{onClick:()=>void I(),disabled:O||!l.trim()&&E.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:O?"Creating...":"Create Scenario"}),w&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:w}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),c("div",{onMouseDown:V,style:{width:"20px",position:"absolute",top:0,left:`${m-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
105
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
106
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
107
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
108
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
109
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Dn,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:k,isStarting:T,isLoading:$,showIframe:D,iframeKey:P,onIframeLoad:_,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Yd=Oe(function(){return n(Rn,{children:n(Od,{})})}),zd=Object.freeze(Object.defineProperty({__proto__:null,default:Yd,loader:Fd,meta:Ld},Symbol.toStringTag,{value:"Module"}));var ie;(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={}))})(ie||(ie={}));function Jo(e,t){return e?Object.values(ie.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Vo=Jo(process.env.DEFAULT_SMALLER_MODEL,ie.Model.OPENAI_GPT4_1_MINI),Bd=Jo(process.env.DEFAULT_LARGER_MODEL,ie.Model.OPENAI_GPT4_1),Ke={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},er={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Ud={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},tr={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},it={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Wd={[ie.Model.OPENAI_GPT5_1]:{id:ie.Model.OPENAI_GPT5_1,provider:Ke,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ie.Model.OPENAI_GPT5]:{id:ie.Model.OPENAI_GPT5,provider:Ke,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_MINI]:{id:ie.Model.OPENAI_GPT5_MINI,provider:Ke,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_NANO]:{id:ie.Model.OPENAI_GPT5_NANO,provider:Ke,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT4_1]:{id:ie.Model.OPENAI_GPT4_1,provider:Ke,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ie.Model.OPENAI_GPT4_1_MINI]:{id:ie.Model.OPENAI_GPT4_1_MINI,provider:Ke,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.OPENAI_GPT4_O]:{id:ie.Model.OPENAI_GPT4_O,provider:Ke,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ie.Model.OPENAI_GPT4_O_MINI]:{id:ie.Model.OPENAI_GPT4_O_MINI,provider:Ke,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:er,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:er,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:er,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ie.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Ud,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:it,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:tr,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:tr,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:tr,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ie.Model.PHIND_CODELLAMA]:{id:ie.Model.PHIND_CODELLAMA,provider:Ke,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.GOOGLE_GEMINI_PRO]:{id:ie.Model.GOOGLE_GEMINI_PRO,provider:it,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:it,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ie.Model.META_CODELLAMA_34B_INSTRUCT,provider:it,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.OPENAI_GPT4_PREVIEW]:{id:ie.Model.OPENAI_GPT4_PREVIEW,provider:Ke,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Ln(e){const t=Wd[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Hd(e){return Ln(e).maxCompletionTokens}function qd(e){return Ln(e).pricing}const ja=1e6;function Gd({model:e,usage:t}){const r=qd(e);return r?t.prompt_tokens*(r.input/ja)+t.completion_tokens*(r.output/ja):null}function Jd({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},o=Gd({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:o?Math.round(o*1e5)/1e5:void 0}}function Vd({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:o}){const s=r??Vo,i=Ln(s);Hd(s);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"&&o?{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const ur="/tmp/codeyam-e2e-tracking";let nr,rr;function Qd(){return nr===void 0&&(nr=process.env.CODEYAM_E2E_TRACK_DATA==="true"),nr}function Kd(){return rr===void 0&&(rr=!process.env.CODEYAM_LLM_FIXTURES_DIR),rr}function Zd(){Q.existsSync(ur)||Q.mkdirSync(ur,{recursive:!0})}function Xd(e){const t=JSON.stringify(e,null,0);return ki.createHash("md5").update(t).digest("hex")}function eu(e,t,r){return[e].join("_")+".json"}function Qo(e,t,r,a){if(!Qd())return;Zd();const o=eu(e),s=ee.join(ur,o),i=Xd(t);if(Kd()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:a,dataHash:i,data:t};Q.writeFileSync(s,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(Q.existsSync(s)){const l=JSON.parse(Q.readFileSync(s,"utf-8")),d={matches:i===l.dataHash,firstRunHash:l.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=mr(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const m=s.replace(".json","_DIFF.json");Q.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:r,scenarioName:a,firstRun:l.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function mr(e,t,r=""){const a=[];if(typeof e!=typeof t)return a.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),a;if(e===null||t===null)return e!==t&&a.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),a;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&a.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const o=Math.max(e.length,t.length);for(let s=0;s<o;s++)a.push(...mr(e[s],t[s],`${r}[${s}]`));return a}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),s=Object.keys(t),i=Array.from(new Set([...o,...s]));for(const l of i){const d=e[l],m=t[l];l in e?l in t?a.push(...mr(d,m,`${r?r+".":""}${l}`)):a.push(`${r?r+".":""}${l}: missing in second run`):a.push(`${r?r+".":""}${l}: missing in first run`)}return a}if(e!==t){const o=JSON.stringify(e),s=JSON.stringify(t);o.length<100&&s.length<100?a.push(`${r||"root"}: ${o} vs ${s}`):a.push(`${r||"root"}: values differ (${o.length} chars vs ${s.length} chars)`)}return a}Cr(vr);const ln=new $i({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),Ra={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},lt={};async function hr({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:o,model:s=Vo,attempts:i=0}){var S,A,k,T,$,D,P;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await tu(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${ln.size}, running=${ln.pending}]`);const l=Date.now();let d,m=0;const u=Ln(s),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 Ii({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:s,responseType:o?"json_schema":a?"json_object":"text",jsonSchema:o},g=Vd(f),y=await ln.add(()=>(d=Date.now(),va(async()=>{const _=Date.now(),I=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],O=setInterval(()=>{const V=Math.floor((Date.now()-_)/1e3),R=Math.floor(V/10)%I.length;Ca(1,`${I[R]} [type=${e}, model=${s}, elapsed=${V}s]`)},1e4);try{return await p.chat.completions.create(g,{timeout:300*1e3})}finally{clearInterval(O)}},{...Ra,onFailedAttempt:_=>{m++,console.log(`CodeYam Error: Completion call failed [model=${s}]`,{error:_,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})),{throwOnTimeout:!0}),x=Date.now(),b=Jd({chatRequest:f,chatCompletion:y,model:s});if(!b)throw new Error("Failed to get LLM call stats");b.retries=m,b.wait_ms=d-l,b.duration_ms=x-l;const v=(S=y.choices)==null?void 0:S[0];let w=null;if(v){if(!v.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");w=(A=v.message)==null?void 0:A.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const E=a?C&&(((k=C.match(/\{[\s\S]*\}/))==null?void 0:k[0])??C):C;if(!E){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:E,rawCompletion:w,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await hr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:s,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(E.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(E)}catch(_){if(console.log("CodeYam Error: Invalid JSON in completion",{error:_.message,model:s,completion:E.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:_.message});const I=`Your previous response contained invalid JSON with the following error:
|
|
110
|
+
|
|
111
|
+
${_.message}
|
|
112
|
+
|
|
113
|
+
Here was your previous response:
|
|
114
|
+
\`\`\`
|
|
115
|
+
${E}
|
|
116
|
+
\`\`\`
|
|
117
|
+
|
|
118
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,O=await ln.add(()=>va(async()=>{const L=Date.now(),G=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],j=setInterval(()=>{const N=Math.floor((Date.now()-L)/1e3),z=Math.floor(N/10)%G.length;Ca(1,`${G[z]} [type=${e}, model=${s}, elapsed=${N}s]`)},1e4);try{return await p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:E},{role:"user",content:I}]},{timeout:300*1e3})}finally{clearInterval(j)}},{...Ra,onFailedAttempt:L=>{console.log("CodeYam Error: Correction call failed",{error:L,attempts:i})}}),{throwOnTimeout:!0}),V=(D=($=(T=O.choices)==null?void 0:T[0])==null?void 0:$.message)==null?void 0:D.content;let R=V;V&&(R=V.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const F=R&&(((P=R.match(/\{[\s\S]*\}/))==null?void 0:P[0])??R);if(!F)throw new Error("Correction attempt returned empty completion");try{JSON.parse(F),console.log("CodeYam: JSON correction successful");const L=Date.now();return b.duration_ms=L-l,{finishReason:O.choices[0].finish_reason,completion:F,stats:b}}catch(L){return console.log("CodeYam Error: Corrected JSON still invalid",{error:L.message,correctedCompletion:F.substring(0,500)}),await hr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:s,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${_.message}`)}return Qo(`completionCall_${e}`,{completion:E,finishReason:y.choices[0].finish_reason}),{finishReason:y.choices[0].finish_reason,completion:E,stats:b}}async function tu(e,t,r){var s,i,l,d,m;const a=await import("fs"),o=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!a.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=a.readdirSync(t).filter(v=>v.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const v of u)try{const w=a.readFileSync(o.join(t,v),"utf-8"),C=JSON.parse(w);h[C.prompt_type]||(h[C.prompt_type]=[]),h[C.prompt_type].push(C)}catch(w){console.warn(`Failed to parse LLM fixture file ${v}:`,w)}for(const v of Object.keys(h))h[v].sort((w,C)=>{const E=w.created_at??0,S=C.created_at??0;return E-S});const p=h[e];if(!p||p.length===0){const v=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${v}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const v=r.match(/Scenario name must match exactly: "([^"]+)"/),w=v==null?void 0:v[1];if(w){const C={};for(const S of p)try{const k=((s=JSON.parse(S.props||"{}").scenario)==null?void 0:s.name)||"__NO_SCENARIO__";C[k]||(C[k]=[]),C[k].push(S)}catch{}const E=C[w];if(E&&E.length>0){const S=`${t}::${e}::${w}`;lt[S]===void 0&&(lt[S]=0);const A=lt[S];lt[S]=(A+1)%E.length,f=E[A],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${w}' [${A+1}/${E.length}]`)}else{const S=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${w}'. Available: [${S}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const v=`${t}::${e}`;lt[v]===void 0&&(lt[v]=0);const w=lt[v];lt[v]=(w+1)%p.length,f=p[w],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${w+1}/${p.length}]`)}let y;try{y=((d=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:d.content)||f.response}catch{y=f.response}let x=y;y&&(x=y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((m=x.match(/\{[\s\S]*\}/))==null?void 0:m[0])??x);return Qo(`completionCall_${e}`,{completion:b||"",finishReason:"stop"}),{finishReason:"stop",completion:b||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function Da(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function nu(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),o=Vt(),s=Date.now(),i={...r,id:o,created_at:s,props:a};let l;const d=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?l=ee.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=ee.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const u=ee.dirname(l);return await Ie.mkdir(u,{recursive:!0}),await Ie.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:o}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=Da();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 ${o} property ${u} with explicit value 'undefined'`);try{return await new Pn().send(new ji({TableName:Da(),Item:Di(i,{removeUndefinedValues:!0})})),{id:o}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new Pn({});new Pn({});new Pn({});const ru=3,au=2,Lr=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+ru*String(t).length*(1+au)});new Nr(Lr());new Nr(Lr());new Nr(Lr());class ou{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var a;return(a=this.byClassAndMethod.get(t))==null?void 0:a.get(r)}}class su{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class iu{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class lu{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class cu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class du{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];if(a.addType(s,"function"),a.addEquivalence(s.withParameter(1),r.withElement("*")),o.args.length>1){const i=o.args[1];a.addEquivalence(s.withParameter(0),i)}}}isComplete(){return!0}}class uu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();o&&o.args.forEach(s=>{a.addEquivalence(t,s)}),a.addType(t,"array"),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class mu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.withReturnValues();a.addType(o,"array")}isComplete(){return!0}}class hu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let s=2;s<o.args.length;s++){const i=o.args[s];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class pu{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let s=0;s<o.args.length;s++)a.addEquivalence(r.withElement("*"),t.withParameter(s))}isComplete(){return!0}}class fu{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addEquivalence(t.withParameter(0),s)}}isComplete(){return!0}}class gu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class yu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class xu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class bu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class vu{getReturnType(){return"object"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"array")}}isComplete(){return!0}}class wu{getReturnType(){return"string[]"}addEquivalences(t,r,a){a.addType(r,"string"),a.addType(t,"string[]"),a.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Cu{getReturnType(){return"unknown"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),s.withProperty("returnValue"))}}isComplete(){return!0}}class Nu{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Su{getReturnType(){return"array"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),o&&o.args.length>0){const s=o.args[0];a.addEquivalence(t.withParameter(0),s)}}isComplete(){return!0}}function Eu(){const e=new ou;return e.register("filter",new su,"Array"),e.register("map",new gu,"Array"),e.register("flatMap",new yu,"Array"),e.register("join",new fu,"Array"),e.register("find",new cu,"Array"),e.register("findLast",new bu,"Array"),e.register("at",new xu,"Array"),e.register("reduce",new du,"Array"),e.register("concat",new uu,"Array"),e.register("slice",new mu,"Array"),e.register("splice",new hu,"Array"),e.register("push",new pu,"Array"),e.register("some",new iu,"Array"),e.register("every",new lu,"Array"),e.register("fromEntries",new vu,"Object"),e.register("split",new wu,"String"),e.register("then",new Cu,"Promise"),e.register("useState",new Su,"React"),e.register("useMemo",new Nu,"React"),e}Eu();class Au{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const o=" ".repeat(this.depth),s=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${s}${o}${r}`,JSON.stringify(a)):console.info(`${s}${o}${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 Au({enabled:!1});const ku=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Pu=new Set(["find","findLast","at","pop","shift"]),Mu=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),_u=new Set([...ku,...Pu,...Mu]),Tu=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Iu=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),$u=new Set([...Tu,...Iu]);[..._u,...$u];new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));function Ko(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 Ri.parse(e)}catch(r){const o=r.message.match(/invalid character .* at (\d+):(\d+)/);if(o){const s=parseInt(o[2],10);if(e.substring(s-2,s-1)==='"')return e=e.substring(0,s-2)+"\\"+e.substring(s-2),Ko(e)}return null}}function ju({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:a}){let o="";return a&&a.length>0&&(o=`
|
|
119
|
+
User-selected Execution Flow Values:
|
|
120
|
+
The user has specifically requested these values be used in the scenario:
|
|
121
|
+
${a.map(s=>` - ${s.path}: ${s.value}${s.isCustom?" (custom value)":""}`).join(`
|
|
122
|
+
`)}
|
|
123
|
+
|
|
124
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
125
|
+
`),`Mock Scenario Data Structure:
|
|
126
|
+
\`\`\`
|
|
127
|
+
${JSON.stringify(r,null,2)}
|
|
128
|
+
\`\`\`
|
|
129
|
+
Existing Mock Scenario Data:
|
|
130
|
+
\`\`\`
|
|
131
|
+
${JSON.stringify(t,null,2)}
|
|
132
|
+
\`\`\`
|
|
133
|
+
${o}
|
|
134
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
135
|
+
`}function Ru({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o}){const s=a.find(i=>i.name===Mn);return`Mock Scenario Data Structure:
|
|
136
|
+
\`\`\`
|
|
137
|
+
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
138
|
+
\`\`\`
|
|
139
|
+
|
|
140
|
+
Existing Mock Scenario Data:
|
|
141
|
+
\`\`\`
|
|
142
|
+
${JSON.stringify(a.map(i=>({name:i.name,data:Yt(s.metadata.data,i.metadata.data)})),null,2)}
|
|
143
|
+
\`\`\`
|
|
144
|
+
|
|
145
|
+
Mock Scenario that should be edited: "${t}"
|
|
146
|
+
${r?`The portion of the data that should be edited:
|
|
147
|
+
\`\`\`
|
|
148
|
+
${JSON.stringify(r,null,2)}
|
|
149
|
+
\`\`\``:""}
|
|
150
|
+
|
|
151
|
+
How this data should be changed: "${e}"
|
|
152
|
+
`}async function Du({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o,flowSelections:s,model:i}){const l=t?Ru({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o}):ju({description:e,existingScenarios:a,scenariosDataStructure:o,flowSelections:s}),d=await hr({type:"guessScenarioDataFromDescription",systemMessage:t?Fu(r):Lu,prompt:l,model:i??Bd});await nu({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o,model:i},...d.stats});const{completion:m}=d;return m?Ko(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Lu=`
|
|
153
|
+
You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
|
|
154
|
+
|
|
155
|
+
Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
|
|
156
|
+
|
|
157
|
+
The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
|
|
158
|
+
|
|
159
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
160
|
+
\`\`\`
|
|
161
|
+
export type ScenarioData = {
|
|
162
|
+
name: string;
|
|
163
|
+
description: string;
|
|
164
|
+
data: {
|
|
165
|
+
mockData: { [key: string]: unknown };
|
|
166
|
+
argumentsData: { [key: string]: unknown };
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
\`\`\`
|
|
171
|
+
`,Fu=e=>`
|
|
172
|
+
You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
|
|
173
|
+
|
|
174
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
175
|
+
${e?`
|
|
176
|
+
We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
|
|
177
|
+
|
|
178
|
+
Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
|
|
179
|
+
|
|
180
|
+
You must respond with valid JSON following this type definition:
|
|
181
|
+
\`\`\`
|
|
182
|
+
{
|
|
183
|
+
data: {
|
|
184
|
+
mockData: { [key: string]: unknown };
|
|
185
|
+
argumentsData: { [key: string]: unknown };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
\`\`\`
|
|
189
|
+
`;async function Ou({request:e}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return U({error:"Missing required field: description or flowSelections"},{status:400});const d=await Du({description:r||"",existingScenarios:a??[],scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:l}),m=(d==null?void 0:d.data)||d;return U({success:!0,data:m})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),U({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Yu=Object.freeze(Object.defineProperty({__proto__:null,action:Ou},Symbol.toStringTag,{value:"Module"}));async function zu(e,t){const r=me();if(!r)return{entityCalls:[],analysisCalls:[]};const a=ee.join(r,".codeyam","llm-calls");try{await Ie.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],s=[];try{const l=(await Ie.readdir(a)).filter(b=>b.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],h=[];for(const b of l)b.startsWith(d)||m&&b.startsWith(m)?u.push(b):h.push(b);const p=u.map(async b=>{try{const v=ee.join(a,b),w=await Ie.readFile(v,"utf-8");return JSON.parse(w)}catch{return null}}),f=h.map(async b=>{try{const v=ee.join(a,b),w=await Ie.readFile(v,"utf-8"),C=JSON.parse(w);return C.object_id===e||t&&C.object_id===t?C:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...g,...y].filter(b=>b!==null);for(const b of x)b.object_id===e?o.push(b):t&&b.object_id===t&&s.push(b);o.sort((b,v)=>v.created_at-b.created_at),s.sort((b,v)=>v.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:s}}async function Bu({params:e,request:t}){const{entitySha:r}=e;if(!r)return U({error:"Entity SHA is required"},{status:400});const o=new URL(t.url).searchParams.get("analysisId")||void 0,s=await zu(r,o);return U(s)}const Uu=Object.freeze(Object.defineProperty({__proto__:null,loader:Bu},Symbol.toStringTag,{value:"Module"}));function Wu(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Me("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Hu(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Hu(e){const t=e.trim().split(`
|
|
190
|
+
`).filter(a=>a.length>0),r=[];for(const a of t){const o=a[0],s=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),l,d=!1,m;if(o==="A"||s==="A")l="added",d=o==="A";else if(o==="M"||s==="M")l="modified",d=o==="M";else if(o==="D"||s==="D")l="deleted",d=o==="D";else if(o==="R"||s==="R"){l="renamed",d=o==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else s==="?"?(l="untracked",d=!1):(l="modified",d=o!==" "&&o!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=pe.join(u,i);try{const p=(g,y)=>{const x=Nt.readdirSync(g,{withFileTypes:!0}),b=[];for(const v of x){const w=pe.join(g,v.name),C=pe.relative(u,w);v.isDirectory()?b.push(...p(w,y)):v.isFile()&&b.push(C)}return b},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 qu(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function Gu(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Me('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return Me("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Me("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function Ju(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
191
|
+
`).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Zo(){const e=me();return e?Wu(e):[]}function Vu(){const e=me();return e?qu(e):null}function Qu(){const e=me();return e?Gu(e):"main"}function Ku(){const e=me();return e?Ju(e):[]}function Xo(e,t){const r=me();return r?Zu(e,t,r):[]}function Zu(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
192
|
+
`).filter(i=>i.length>0).map(i=>{const 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(o){return console.error("Failed to get branch diff:",o),[]}}function Xu(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let o="";try{o=Nt.readFileSync(pe.join(r,e),"utf8")}catch(s){console.error(`Failed to read current file ${e}:`,s),o=""}return{oldContent:a,newContent:o,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function em(e){const t=me();return t?Xu(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function tm(e,t,r,a){const o=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Me(`git show ${t}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:s,newContent:i,fileName:e}}catch(s){return console.error(`Failed to get branch diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function mn(e,t,r){const a=me();return a?tm(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function La(e,t){var r,a;try{return((a=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:a.trim())??null}catch(o){return console.error(`Failed to get commit SHA for ${e}:`,o),""}}function nm(e,t,r,a){const o=br.createHash("sha256");return o.update(`${e}:${t}:${r}:${a}`),o.digest("hex").substring(0,16)}function es(){const e=me();if(!e)throw new Error("No project root found");const t=pe.join(e,".codeyam","cache","branch-entity-diff");return Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),t}function rm(e){try{const t=es(),r=pe.join(t,`${e}.json`);if(!Nt.existsSync(r))return null;const a=Nt.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function am(e,t){try{const r=es(),a=pe.join(r,`${e}.json`);Nt.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function om(e,t,r){const a=fn(t,e),o=fn(r,e),s=new Map(a.map(u=>[u.name,u])),i=new Map(o.map(u=>[u.name,u])),l=[],d=[],m=[];for(const[u,h]of i){const p=s.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 s)i.has(u)||m.push(h);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:m}}function sm(e,t){const r=me();if(!r)throw new Error("No project root found");const a=La(e,r),o=La(t,r);if(!a||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const s=nm(e,t,a,o),i=rm(s);if(i)return console.log(`Using cached branch entity diff: ${s}`),i;const l=Xo(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=mn(u.path,e,t),p=fn(h.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const h=mn(u.path,e,t),p=fn(h.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=mn(u.path,e,t),p=om(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:o,fileComparisons:d,cacheKey:s,computedAt:new Date().toISOString()};return am(s,m),m}function im({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return U({error:"Missing required parameters: base and compare"},{status:400});const o=sm(r,a);return U(o)}catch(t){return console.error("Failed to compute branch entity diff:",t),U({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const lm=Object.freeze(Object.defineProperty({__proto__:null,loader:im},Symbol.toStringTag,{value:"Module"}));async function cm({request:e}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:o,viewportWidth:s=1440}=t;if(!r||!a||!o)return U({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=me();if(!i)return U({error:"Project root not found"},{status:500});const l=ee.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:o,projectRoot:i,viewportWidth:s}),m=await new Promise(p=>{const f=ee.join(i,".codeyam","db.sqlite3"),g=kn("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",x="";g.stdout.on("data",b=>{const v=b.toString();y+=v;const w=v.trim().split(`
|
|
193
|
+
`);for(const C of w)C.includes("[Capture]")&&console.log(C)}),g.stderr.on("data",b=>{const v=b.toString();x+=v,console.error("[Capture:Error]",v.trim())}),g.on("close",b=>{p(b===0?{success:!0,output:y}:{success:!1,output:y,error:x||`Process exited with code ${b}`})}),g.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),p({success:!1,output:"",error:b.message})})});if(!m.success)return U({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return U({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return U(h)}catch(t){return console.error("[Capture] Error:",t),U({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const dm=Object.freeze(Object.defineProperty({__proto__:null,action:cm},Symbol.toStringTag,{value:"Module"}));async function um(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=be(),s=a.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",s).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await o.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",s).execute(),console.log(`[recapture] Updated defaultWidth for entity ${s} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await $t(e,g=>{if(g){if(g.readyToBeCaptured=!0,g.scenarios)for(const y of g.scenarios)delete y.finishedAt,delete y.startedAt,delete y.screenshotStartedAt,delete y.screenshotFinishedAt,delete y.interactiveStartedAt,delete y.interactiveFinishedAt,delete y.error,delete y.errorStack;delete g.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=me();if(!d)throw new Error("Project root not found");const m=ee.join(d,".codeyam","config.json"),u=JSON.parse(Q.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 mm(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=(u=a.scenarios)==null?void 0:u.find(h=>h.id===t);if(!o)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: ${o.name}`),await $t(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const p=h.scenarios.find(f=>f.name===o.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${o.name} for recapture`);const s=me();if(!s)throw new Error("Project root not found");const i=ee.join(s,".codeyam","config.json"),l=JSON.parse(Q.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId: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}}async function hm({request:e,context:t}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await st()),!r)return U({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o||!s)return U({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${s}`);const i=await mm(o,s,r);return console.log("[API] Scenario recapture queued",i),U({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),U({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const pm=Object.freeze(Object.defineProperty({__proto__:null,action:hm},Symbol.toStringTag,{value:"Module"}));async function fm({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=$n(r);try{return await Ni(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(o){console.error("[api.logs] Error clearing log file:",o);const s=o instanceof Error?o.message:String(o);return new Response(`Error clearing log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function gm({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=$n(t);try{if(!gi(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 Si(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 o=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const ym=Object.freeze(Object.defineProperty({__proto__:null,action:fm,loader:gm},Symbol.toStringTag,{value:"Module"}));async function xm(e,t){var s,i,l,d,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await $e();const r=await at({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(s=r.scenarios)==null?void 0:s.find(h=>h.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 o={returnValue:{status:"success",data:((d=(l=(i=a.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(m=a.metadata)==null?void 0:m.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),o}async function bm({request:e}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return U({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const o=await xm(r,a);return console.log("[API] Function execution completed successfully"),U({success:!0,result:o})}catch(t){return console.log("[API] Error during function execution:",t),U({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const vm=Object.freeze(Object.defineProperty({__proto__:null,action:bm},Symbol.toStringTag,{value:"Module"}));function wm({request:e}){return U({status:"ok"})}async function Cm({request:e,context:t}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await st()),!r)return console.error("[Interactive Mode API] Queue not initialized"),U({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("action"),s=a.get("analysisId"),i=a.get("scenarioId");if(!o||!s)return U({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return U({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Ye();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return U({error:"Project not initialized"},{status:500});if(o==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:s,scenarioId:i,projectSlug:l});return U({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:s,projectSlug:l});return U({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",s),U({error:"Failed to control interactive mode",details:o},{status:500})}}const Nm=Object.freeze(Object.defineProperty({__proto__:null,action:Cm,loader:wm},Symbol.toStringTag,{value:"Module"}));async function Sm({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 o=me();if(o)for(const s of a){const i=pe.join(o,".codeyam","captures","screenshots",s);try{await xe.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 $l({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 Em=Object.freeze(Object.defineProperty({__proto__:null,action:Sm},Symbol.toStringTag,{value:"Module"})),qt="/tmp/codeyam",pr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",ts=500,Am=ts*1024*1024;function bt(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function hn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function km(e){return bt("config user.email",e)}function Pm(e){const t=ee.join(e,".codeyam","debug-report.md");if(!Q.existsSync(t))return null;try{return Q.readFileSync(t,"utf8")}catch{return null}}function Mm(e,t=20){const r=ee.join(qt,"local-dev",e,"codeyam","log.txt");if(!Q.existsSync(r))return[];try{return Q.readFileSync(r,"utf8").split(`
|
|
194
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function _m(e){try{const t=await fetch(`${pr}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function Tm(e,t){try{Me(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function Im(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:o,screenshot:s,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),m=ee.join(qt,`delta-staging-${d}`),u=ee.join(m,"delta");Q.mkdirSync(u,{recursive:!0});try{const h=bt("diff --binary HEAD",t)||"";Q.writeFileSync(ee.join(u,"tracked.patch"),h?h+`
|
|
195
|
+
`:"");const p=bt("ls-files --others --exclude-standard",t);if(p){const x=ee.join(u,"untracked");Q.mkdirSync(x,{recursive:!0});for(const b of p.split(`
|
|
196
|
+
`).filter(Boolean)){const v=ee.join(t,b),w=ee.join(x,b);if(Q.existsSync(v)){const C=ee.dirname(w);Q.mkdirSync(C,{recursive:!0}),Q.statSync(v).isFile()&&Q.copyFileSync(v,w)}}}const f=ee.join(t,".codeyam");if(Q.existsSync(f)){const x=ee.join(u,"codeyam");Q.cpSync(f,x,{recursive:!0})}Q.writeFileSync(ee.join(u,"meta.json"),JSON.stringify(o,null,2));const g=ee.join(qt,"local-dev",r,"codeyam","log.txt");Q.existsSync(g)?Q.copyFileSync(g,ee.join(u,"codeyam-log.txt")):Q.writeFileSync(ee.join(u,"codeyam-log.txt"),`# Log file not found
|
|
197
|
+
`);const y=ee.join(t,".codeyam","debug-report.md");Q.existsSync(y)&&(Q.copyFileSync(y,ee.join(u,"debug-report.md")),l("Debug report included")),s&&s.length>0&&(Q.writeFileSync(ee.join(u,"screenshot.jpg"),s),l(`Screenshot included (${hn(s.length)})`));try{Me(`tar -czf "${a}" -C "${m}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{Q.rmSync(m,{recursive:!0,force:!0})}}async function $m(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:o,onProgress:s}=e,i=s||(()=>{});i("Gathering metadata...");const l=bt("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=bt("rev-parse --abbrev-ref HEAD",t)||"unknown",m=bt("status --porcelain",t),u=bt("remote get-url origin",t),h=m!==null&&m.length>0,p=Yo(r),f=Pm(t);let g=a;f&&(g={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam:diagnose workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:d,isDirty:h,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},x=Date.now(),b=ee.join(qt,`base-${l}-${x}.tar.gz`),v=ee.join(qt,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const w=await _m(l);let C=null;w?i("Server already has base, skipping..."):(i("Generating base archive..."),Tm(t,b),C=Q.statSync(b).size,i(`Base archive: ${hn(C)}`)),i("Generating delta archive..."),Im({projectRoot:t,projectSlug:r,outputPath:v,metadata:y,screenshot:o,onProgress:s});const S=Q.statSync(v).size;i(`Delta archive: ${hn(S)}`);const A=(C||0)+S;if(A>Am)throw Q.existsSync(b)&&Q.unlinkSync(b),Q.unlinkSync(v),new Error(`Bundle too large: ${hn(A)} (max: ${ts} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:w?null:b,deltaPath:v,metadata:y,baseSha:l,baseSize:C,deltaSize:S}}async function jm(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:o,baseSha:s,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),m=Q.statSync(r),u=t?Q.statSync(t):null,h=m.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${pr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:h,baseSha:s,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:o.timestamp,git:o.git,versions:o.versions,system:o.system,feedback:o.feedback}})});if(!p.ok){const w=await p.json();throw new Error(w.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await p.json(),x=[];if(t&&y){d("Uploading base...");const w=Q.readFileSync(t);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const b=Q.readFileSync(r);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(w=>{if(!w.ok)throw new Error(`Delta upload failed: ${w.status}`)})),await Promise.all(x),d("Confirming upload...");const v=await fetch(`${pr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const w=await v.json();throw new Error(w.error||`Confirm failed: ${v.status}`)}return t&&Q.existsSync(t)&&Q.unlinkSync(t),Q.unlinkSync(r),{bundleId:f}}async function Rm({request:e}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),o=t.get("email"),s=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("entityName"),h=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),g=t.get("screenshot");let y=a||void 0;!y&&u&&(p?y=`Issue on ${u} scenario "${p}"`:y=`Issue on ${u}`);let x;if(g&&g.size>0){const A=await g.arrayBuffer();x=Buffer.from(A),console.log(`[Bundle] Screenshot received: ${g.size} bytes`)}const b=me();if(!b)return U({error:"Project root not found"},{status:500});const v=await Ye();if(!v)return U({error:"Project slug not found"},{status:500});const w={issueType:r||"other",description:y,email:o||void 0,source:s||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:Mm(v,20),entityName:u||void 0,entityType:h||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${v}...`),console.log(`[Bundle] Context: ${w.source}, issue: ${w.issueType}`);const C=await $m({projectRoot:b,projectSlug:v,feedback:w,screenshot:x,onProgress:A=>{console.log(`[Bundle] ${A}`)}}),E=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const S=await jm({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:v,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:A=>{console.log(`[Bundle] ${A}`)}});return console.log(`[Bundle] Upload complete: ${S.bundleId}`),U({success:!0,reportId:S.bundleId,size:E})}catch(t){return console.error("[Bundle] Error:",t),U({error:t.message||"Failed to generate bundle"},{status:500})}}function Dm(){const e=me(),t=e?km(e):null;return U({defaultEmail:t})}const Lm=Object.freeze(Object.defineProperty({__proto__:null,action:Rm,loader:Dm},Symbol.toStringTag,{value:"Module"})),Fa=Cr(vr);async function Fm({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(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const o=await Promise.all(a.map(async s=>{const i=Om(s),l=i?await Ym(s):null;return{pid:s,isRunning:i,processName:l}}));return Response.json({processes:o})}function Om(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ym(e){try{const{stdout:t}=await Fa(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await Fa(`ps -p ${e} -o args=`),a=r.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const zm=Object.freeze(Object.defineProperty({__proto__:null,loader:Fm},Symbol.toStringTag,{value:"Module"})),Bm=wr(import.meta.url),Um=ee.dirname(Bm);function Wm({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Bo(),r=me()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const a=(t==null?void 0:t.port)||3111,o=ee.join(Um,"..","..","..","..","webserver","bootstrap.js"),s=ee.join(r,".codeyam","logs");Q.existsSync(s)||Q.mkdirSync(s,{recursive:!0});const i=Q.openSync(ee.join(s,"background-server.log"),"a"),l=Q.openSync(ee.join(s,"background-server-error.log"),"a"),d=new Date().toISOString();Q.appendFileSync(ee.join(s,"background-server.log"),`
|
|
198
|
+
[${d}] Server restart requested via dashboard
|
|
199
|
+
`),jc();const m=kn("node",[o],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});m.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${m.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const Hm=Object.freeze(Object.defineProperty({__proto__:null,action:Wm},Symbol.toStringTag,{value:"Module"}));async function qm({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)=>{var h,p,f,g,y;const m=(p=(h=l.metadata)==null?void 0:h.data)==null?void 0:p.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:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(y=(g=l.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const o=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),s=await Ql(o);if(!s||s.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 ${s.length} scenarios to database`),s.forEach((l,d)=>{var u,h;const m=(h=(u=l.metadata)==null?void 0:u.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...r,scenarios:s};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 Gm=Object.freeze(Object.defineProperty({__proto__:null,action:qm},Symbol.toStringTag,{value:"Module"}));async function Jm({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:o}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Oa(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=Oa(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(o)try{await ct({commitSha:o,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 Oa(e){try{return process.kill(e,0),!0}catch{return!1}}const Vm=Object.freeze(Object.defineProperty({__proto__:null,action:Jm},Symbol.toStringTag,{value:"Module"}));async function Qm({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=me();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=pe.join(r,".codeyam","captures","screenshots",t);try{await xe.access(a);const o=await xe.readFile(a),s=pe.extname(a).toLowerCase(),i=s===".png"?"image/png":s===".jpg"||s===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Km=Object.freeze(Object.defineProperty({__proto__:null,loader:Qm},Symbol.toStringTag,{value:"Module"})),Ya={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function Fr({type:e,className:t=""}){const r=Ya[e]||Ya.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const Zm={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function cn({variant:e,pid:t,label:r,className:a=""}){const o=Zm[e],s=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${a}`,style:{backgroundColor:o.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:o.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:s})})}function De({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:o}){const[s,i]=M("loading"),[l,d]=M(!1),m=Se(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ne(()=>{i("loading"),d(!1);const f=m.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:o,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"}}),s==="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"})})}),s==="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:o,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let za=!1;function Xm(){if(za)return;const e=document.createElement("style");e.textContent=`
|
|
200
|
+
@keyframes strongPulse {
|
|
201
|
+
0%, 100% { opacity: 0.2; }
|
|
202
|
+
50% { opacity: 1; }
|
|
203
|
+
}
|
|
204
|
+
`,document.head.appendChild(e),za=!0}function Or({size:e="medium",className:t=""}){typeof document<"u"&&Xm();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:o,gap:s}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${s}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${o}px`,height:`${o}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function eh({request:e,context:t,params:r}){var L,G,j,N,z,W,H,re;let a=t.analysisQueue;a||(a=await st());const o=new URL(e.url),s=parseInt(o.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return U({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:s,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),m=await Ye();let u=null;if(m&&((L=d==null?void 0:d.currentlyExecuting)!=null&&L.commitSha)){const{project:J,branch:Y}=await Fe(m),q=await gn({projectId:J.id,branchId:Y.id,shas:[d.currentlyExecuting.commitSha]});u=q&&q.length>0?q[0]:null}else u=await Mt();const h=async J=>{const Y=await At(J);if(!Y)return null;const{getAnalysesForEntity:q}=await Promise.resolve().then(()=>dc),K=await q(J,!1);return{...Y,analyses:K||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async J=>{const Y=[];if(J.entityShas&&J.entityShas.length>0){const q=J.entityShas.map(B=>h(B)),K=await Promise.all(q);Y.push(...K.filter(B=>B!==null))}return{...J,entities:Y}}));let f=null;if(d!=null&&d.currentlyExecuting){const J=d.currentlyExecuting,Y=[];if(J.entityShas&&J.entityShas.length>0){const q=J.entityShas.map(B=>h(B)),K=await Promise.all(q);Y.push(...K.filter(B=>B!==null))}f={...J,entities:Y}}const g=f?p.filter(J=>J.id!==f.id):p,y=((j=(G=u==null?void 0:u.metadata)==null?void 0:G.currentRun)==null?void 0:j.currentEntityShas)||[],b=(await Promise.all(y.map(J=>h(J)))).filter(J=>J!==null),v=[];if(m)try{const{project:J,branch:Y}=await Fe(m),q=await gn({projectId:J.id,branchId:Y.id,limit:100});for(const K of q){const B=((N=K.metadata)==null?void 0:N.historicalRuns)||[];v.push(...B)}}catch(J){console.error("[activity.tsx] Failed to load historical runs from commits:",J)}const w=[...v].sort((J,Y)=>{const q=J.lastCaptureAt||J.analysisCompletedAt||J.archivedAt||J.createdAt||"";return(Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"").localeCompare(q)}),C=(s-1)*i,E=C+i,S=w.slice(C,E),A=Math.ceil(w.length/i),k=await Promise.all(S.map(async J=>{const Y=J.currentEntityShas||[];if(Y.length===0)return{...J,entities:[]};const q=await Promise.all(Y.map(K=>h(K)));return{...J,entities:q.filter(K=>K!==null)}})),T=!!f,$=g.length,D=w.filter(J=>{const Y=!!J.failedAt,q=J.readyToBeCaptured,K=J.capturesCompleted??0,B=q===void 0?!0:q===0||K>=q;return!Y&&!!J.analysisCompletedAt&&B}),P=new Set(((z=f==null?void 0:f.entities)==null?void 0:z.map(J=>J.sha))||[]),_=D.filter(J=>!(J.currentEntityShas||[]).some(q=>P.has(q))),O=(await Promise.all(_.slice(0,3).map(async J=>{const Y=J.currentEntityShas||[];if(Y.length===0)return{run:J,entities:[]};const q=await Promise.all(Y.map(K=>h(K)));return{run:J,entities:q.filter(K=>K!==null)}}))).flatMap(({run:J,entities:Y})=>Y.map(q=>({...q,runId:J.id,completedAt:J.lastCaptureAt||J.analysisCompletedAt||J.archivedAt||J.createdAt})));let V=[],R=null,F=null;if((H=(W=u==null?void 0:u.metadata)==null?void 0:W.currentRun)!=null&&H.analysisCompletedAt&&b.length>0){const J=b[0].sha;R=b[0];const Y=await Tn(J);Y&&Y.length>0&&Y[0].scenarios&&(V=Y[0].scenarios,F=Y[0].status)}return U({state:{...d,jobs:g,currentlyExecuting:f},currentRun:(re=u==null?void 0:u.metadata)==null?void 0:re.currentRun,historicalRuns:k,totalHistoricalRuns:w.length,currentPage:s,totalPages:A,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:T,queuedCount:$,recentCompletedEntities:O,hasMoreCompletedRuns:_.length>3,currentEntityScenarios:V,currentEntityForScenarios:R,currentAnalysisStatus:F})}function th({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const o=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:o.map(s=>{const i=e===s.id;return n(ae,{to:s.id==="current"?"/activity":`/activity/${s.id}`,className:`
|
|
205
|
+
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
206
|
+
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
207
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[s.label,s.count!==null&&s.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s.count}),s.count===null&&s.hasContent&&n("span",{className:`
|
|
208
|
+
inline-block w-2 h-2 rounded-full
|
|
209
|
+
${i?"":"bg-gray-400"}
|
|
210
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},s.id)})})})}function nh({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:o,onShowLogs:s,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:m,currentAnalysisStatus:u}){var I,O,V,R;const[h,p]=M({}),[f,g]=M({isKilling:!1,current:0,total:0}),y=nt(),x=!!e,b=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),w=v&&!!(t!=null&&t.capturePid),C=!v,E=x,S=d||[],{lastLine:A}=ht(a,E);ne(()=>{if(!t)return;const F=[t.analyzerPid,t.capturePid].filter(N=>!!N);if(F.length===0)return;let L=!0;const G=async()=>{try{const z=await(await fetch(`/api/process-status?pids=${F.join(",")}`)).json();if(z.processes&&L){const W={};z.processes.forEach(H=>{W[H.pid]={isRunning:H.isRunning,processName:H.processName}}),p(W)}}catch(N){L&&console.error("Failed to fetch process statuses:",N)}};G();const j=setInterval(()=>void G(),5e3);return()=>{L=!1,clearInterval(j)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[k,T]=M(!1),[$,D]=M(!1);ne(()=>{b.length<=3&&k&&T(!1)},[b.length,k]),ne(()=>{i.length<=3&&$&&D(!1)},[i.length,$]);const P=k?b:b.slice(0,3),_=b.length>3;return c("div",{className:"flex flex-col gap-[45px]",children:[E?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(Ze,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:w?"Capturing...":"Analyzing..."})]}),P.map(F=>c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[c("div",{className:"flex items-center gap-3",children:[n("div",{children:n(Ue,{type:F.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col gap-[1px]",children:[c("div",{className:"flex items-center gap-[14px]",children:[n(ae,{to:`/entity/${F.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:F.name}),F.entityType&&n(Fr,{type:F.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:F.filePath,children:F.filePath})]})]}),n("button",{onClick:s,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},F.sha)),_&&!k&&c("button",{onClick:()=>T(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",b.length-3," more"," ",b.length-3===1?"entity":"entities"]}),k&&_&&n("button",{onClick:()=>T(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),w&&S&&S.length>0&&m&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(F=>{var H,re,J,Y;if(!F.id)return null;const L=(re=(H=F.metadata)==null?void 0:H.screenshotPaths)==null?void 0:re[0],G=(J=F.metadata)==null?void 0:J.noScreenshotSaved,j=L&&!G,N=(Y=u==null?void 0:u.scenarios)==null?void 0:Y.find(q=>q.name===F.name),W=N&&N.screenshotStartedAt&&!N.screenshotFinishedAt||!j&&!G;return n(ae,{to:`/entity/${m.sha}/scenarios/${F.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:W?"#f9f9f9":void 0,borderColor:W?"#efefef":"#ccc"},children:j?n(De,{screenshotPath:L,alt:F.name,className:"w-full h-full object-contain bg-gray-100"}):W?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Or,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},F.id)})}),A&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(cn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||((I=h[t.analyzerPid])==null?void 0:I.isRunning))&&n(cn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(cn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(w||((O=h[t.capturePid])==null?void 0:O.isRunning))&&n(cn,{variant:"running"})]}),(((V=h[t==null?void 0:t.analyzerPid])==null?void 0:V.isRunning)||((R=h[t==null?void 0:t.capturePid])==null?void 0:R.isRunning))&&n("button",{onClick:()=>{const F=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(j=>{var N;return!!j&&((N=h[j])==null?void 0:N.isRunning)});if(F.length===0)return;const L=F.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${L})?`))return;g({isKilling:!0,current:1,total:F.length}),(async()=>{for(let j=0;j<F.length;j++){const N=F[j];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:N,commitSha:o||""})})}catch(z){console.error(`Failed to kill process ${N}:`,z)}j<F.length-1&&g({isKilling:!0,current:j+2,total:F.length})}g({isKilling:!1,current:0,total:0}),y.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Js,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),c("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(ae,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(ae,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),c(ae,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),c("div",{className:"flex flex-col gap-4",children:[($?i:i.slice(0,3)).map(F=>{var j;const L=(j=F.analyses)==null?void 0:j[0],G=(L==null?void 0:L.scenarios)||[];return L==null||L.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Ue,{type:F.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(ae,{to:`/entity/${F.sha}`,className:"hover:underline cursor-pointer",title:F.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:F.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:F.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:F.filePath,children:F.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:s,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:N=>{N.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:N=>{N.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),G.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:G.map(N=>{var re,J,Y;if(!N.id)return null;const z=(J=(re=N.metadata)==null?void 0:re.screenshotPaths)==null?void 0:J[0],W=(Y=N.metadata)==null?void 0:Y.noScreenshotSaved,H=z&&!W;return c("div",{className:"shrink-0 flex flex-col gap-2",children:[n(ae,{to:`/entity/${F.sha}/scenarios/${N.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:H?"#f3f4f6":"#FAFAFA",borderColor:H?"#d1d5db":"#BCCDD3",borderStyle:H?"solid":"dashed"},onMouseEnter:q=>{H&&(q.currentTarget.style.borderColor="#005C75",q.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:q=>{q.currentTarget.style.borderColor=H?"#d1d5db":"#BCCDD3",q.currentTarget.style.boxShadow="none"},children:H?n(De,{screenshotPath:z,alt:N.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:N.name})]},N.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},F.sha)}),i.length>3&&!$&&c("button",{onClick:()=>D(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),$&&i.length>3&&n("button",{onClick:()=>D(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function rh({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Vs,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),c(ae,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[a,o]=M(null),[s,i]=M(null),[l,d]=M(null),[m,u]=M(!1),[h,p]=M(!1),[f,g]=M(new Set),y=nt();ne(()=>{e.length<=3&&h&&p(!1)},[e.length,h]);const x=S=>{o(S)},b=(S,A)=>{S.preventDefault(),i(A)},v=async(S,A)=>{if(S.preventDefault(),!a){i(null);return}const k=e.findIndex(D=>D.id===a);if(k===-1){o(null),i(null);return}if(k===A){o(null),i(null);return}const T=k<A?"down":"up",$=Math.abs(A-k);u(!0);try{for(let D=0;D<$;D++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:T})});y.revalidate()}catch(D){console.error("Failed to reorder job:",D)}finally{u(!1),o(null),i(null)}},w=()=>{m||(o(null),i(null))},C=async S=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:S})}),window.location.reload()}catch(A){console.error("Failed to cancel job:",A)}},E=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(S){console.error("Failed to cancel jobs:",S)}};return c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void E(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),c("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(S=>{var _,I,O,V;const A=e.findIndex(R=>R.id===S.id),k=l===A,T=a===S.id,$=s===A,D=f.has(S.id),P=((_=S.entities)==null?void 0:_.length)>0?D?S.entities:S.entities.slice(0,3):[];return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:T||m?.5:1,transform:$&&a!==null&&!T?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":T?"grabbing":"grab"},onMouseEnter:()=>d(A),onMouseLeave:()=>d(null),draggable:!m,onDragStart:R=>{x(S.id),R.dataTransfer.effectAllowed="move"},onDragOver:R=>b(R,A),onDrop:R=>void v(R,A),onDragEnd:w,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Qs,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",A+1]})]}),c("div",{className:"flex flex-col gap-2 mt-8",children:[P.length>0?c(ce,{children:[P.map(R=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Ue,{type:R.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(ae,{to:`/entity/${R.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:R.name}),R.entityType&&n(Fr,{type:R.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:R.filePath})]})]})})},R.sha)),((I=S.entities)==null?void 0:I.length)>3&&n("button",{onClick:()=>{g(R=>{const F=new Set(R);return F.has(S.id)?F.delete(S.id):F.add(S.id),F})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:D?"Show less":`+${S.entities.length-3} more ${S.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Ks,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((O=S.entityNames)==null?void 0:O[0])||(S.type==="analysis"?"Analysis Job":S.type==="recapture"?"Recapture Job":S.type==="debug-setup"?"Debug Setup":S.type.charAt(0).toUpperCase()+S.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((V=S.filePaths)==null?void 0:V[0])||(S.filePaths&&S.filePaths.length>1?`${S.filePaths.length} files`:S.entityShas&&S.entityShas.length>0?`${S.entityShas.length} ${S.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),c("div",{className:"flex items-center justify-end gap-2 mt-1",children:[k&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Zs,{size:20})}),n("button",{onClick:()=>void C(S.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},S.id)}),e.length>3&&!h&&c("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function ah({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:o,onShowLogs:s}){if(t===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Xs,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),c(ae,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=M(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(h=>{d.push({...h,runCreatedAt:u.createdAt})})});const m=i?d:d.slice(0,3);return c("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var g;const h=(g=u.analyses)==null?void 0:g[0],p=(h==null?void 0:h.scenarios)||[],f=!u.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(Ue,{type:u.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(ae,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:s,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(y=>{var w,C,E;if(!y.id)return null;const x=(C=(w=y.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],b=(E=y.metadata)==null?void 0:E.noScreenshotSaved,v=x&&!b;return n(ae,{to:`/entity/${u.sha}/scenarios/${y.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:v?"#ccc":"#BCCDD3",borderStyle:v?"solid":"dashed"},children:v?n(De,{screenshotPath:x,alt:y.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},y.id)}),p.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&c("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const oh=Oe(function(){const t=We(),r=eo(),[a,o]=M(!1);mt({source:"activity-page"});const s=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(th,{activeTab:s,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),s==="current"&&n(nh,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),s==="queued"&&n(rh,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),s==="historic"&&n(ah,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:s,onShowLogs:()=>o(!0)}),a&&t.projectSlug&&n(dt,{projectSlug:t.projectSlug,onClose:()=>o(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),sh=Object.freeze(Object.defineProperty({__proto__:null,default:oh,loader:eh},Symbol.toStringTag,{value:"Module"}));async function ns(e,t,r){var C,E;await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=me();if(!o)throw new Error("Project root not found");const s=ee.join(o,".codeyam","config.json"),i=JSON.parse(Q.readFileSync(s,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=$n(l);try{Q.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Fe(l),u=((C=m.metadata)==null?void 0:C.packageManager)||"npm",h=3112,p=ot(l),f=((E=m.metadata)==null?void 0:E.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=Tl({filePath:a.filePath,webapps:f,environmentVariables:g,port:h,packageManager:u});await $t(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const A of S.scenarios)(!t||A.name===t)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=y.startCommand,v={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{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 ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:l,port:h,packageManager:u,framework:y.framework,instructions:v}}async function ih({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),o=r.searchParams.get("scenarioId")||void 0;if(!a)return U({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let s=t.analysisQueue;if(s||(s=await st()),!s)return U({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:o});try{const i=await ns(a,o,s);return U({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),U({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function lh({request:e,context:t}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await st()),!r)return U({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o)return U({error:"Missing required field: analysisId"},{status:400});const i=await ns(o,s,r);return U({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",s),U({error:"Failed to setup debug environment",details:o},{status:500})}}const ch=Object.freeze(Object.defineProperty({__proto__:null,action:lh,loader:ih},Symbol.toStringTag,{value:"Module"}));async function dh({request:e,context:t}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await st()),!r)return U({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("defaultWidth");if(!o||!s)return U({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(s,10);if(isNaN(i)||i<320||i>3840)return U({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const l=await um(o,i,r);return console.log("[API] Recapture queued",l),U({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),U({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const uh=Object.freeze(Object.defineProperty({__proto__:null,action:dh},Symbol.toStringTag,{value:"Module"}));function mh(e,t){var i,l,d,m,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||p?a?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:a?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const o=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||o){const h=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}: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 hh(e){return mh(e).hasOutdatedSimulations}function Fn(e,t,r,a,o){var R,F,L,G,j,N,z,W;const s=(R=t==null?void 0:t.scenarios)==null?void 0:R.find(H=>H.name===e.name),i=!!(s!=null&&s.startedAt),l=!!(s!=null&&s.screenshotStartedAt),d=!!(s!=null&&s.screenshotFinishedAt),m=!!(s!=null&&s.finishedAt),u=1800*1e3,h=l&&!d&&(s==null?void 0:s.screenshotStartedAt)&&Date.now()-new Date(s.screenshotStartedAt).getTime()>u,p=!!((L=(F=e.metadata)==null?void 0:F.screenshotPaths)!=null&&L[0])||!!((G=e.metadata)!=null&&G.executionResult),f=l&&!d,g=s==null?void 0:s.error,y=(N=(j=e.metadata)==null?void 0:j.executionResult)==null?void 0:N.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const H of t.errors)x.push({source:`${H.phase} phase`,message:H.message});if(t!=null&&t.steps)for(const H of t.steps)H.error&&x.push({source:H.name,message:H.error});const b=!p&&!g&&!y&&x.length>0,v=!!(g||y||h||b),w=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(b?`Analysis error: ${x[0].message}`:null),C=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(s==null?void 0:s.errorStack)||(y==null?void 0:y.stack)||null,S=(a&&o?o.jobs.some(H=>{var re;return((re=H.entityShas)==null?void 0:re.includes(a))||H.type==="analysis"&&H.entityShas&&H.entityShas.length===0})||((W=(z=o.currentlyExecuting)==null?void 0:z.entityShas)==null?void 0:W.includes(a)):!1)&&!i&&!v||!!(s!=null&&s.analyzing)&&!i&&!v,A=i&&!l&&!m&&!v,k=(S||A||f)&&!v,T=(S||A)&&r===!1&&!p;let $;T?$="crashed":v?$="error":p||m?$="completed":f?$="capturing":A?$="starting":S?$="queued":$="pending";let D="📷",P="pending",_=!1,I=`Not captured: ${e.name}`;const O="border-gray-300",V=v||T?"bg-red-50":"bg-white";return v||T?(D="⚠️",P="error",I=`Error: ${T?"Analysis process crashed":w||"Unknown error"}`):S?(D="⋯",P="queued",I=`Queued: ${e.name}`):A?(D="⋯",P="starting",_=!0,I=`Starting server for ${e.name}...`):f&&!v?(D="⋯",P="capturing",_=!0,I=`Capturing ${e.name}...`):p&&(D="✓",P="completed",I=e.name),{hasError:v||T,errorMessage:T?"Analysis process crashed":w,errorStack:T?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:p,hasCrashed:T,isAnalyzing:k,isQueued:S,isServerStarting:A,status:$,icon:D,iconType:P,shouldSpin:_,title:I,borderColor:O,bgColor:V}}function rs({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:o=!1}){var C,E,S,A,k,T;const s=Fn(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,l=!!i,m=(((S=(E=e.metadata)==null?void 0:E.data)==null?void 0:S.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((k=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:k.length)||0,p=((T=i==null?void 0:i.timing)==null?void 0:T.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]"},x=s.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?o?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=a?`border-2 ${x.border}`:"",v=Array.from({length:3},($,D)=>n("div",{className:`w-1 h-1 rounded-full ${D<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},D)),w=s.hasError?`Error: ${s.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
211
|
+
${m} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
|
|
212
|
+
${p}ms`:`Not executed: ${e.name}`;return c(ae,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${b} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:w,onClick:$=>$.stopPropagation(),children:[n("div",{className:`${x.icon} ${g.iconSize} font-mono font-bold`,children:s.hasError?"⚠":l?"ƒ":"○"}),l&&!s.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!s.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),l&&!s.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!s.hasError&&h>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function fr({size:e=24,className:t=""}){return c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Ba({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:o,size:s="medium",cacheBuster:i,className:l="",viewMode:d}){var y,x;if(t.entityType==="library")return n(rs,{scenario:e,entitySha:t.sha,size:s==="small"?"small":"medium"});const u=Fn(e,r,o,t.sha,a),h=s==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:s==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${b}/${d}`:b};if(u.isCaptured){const b=(x=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return n(ae,{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(De,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const b={size:s==="small"?16:s==="large"?24:20,strokeWidth:2},v=n(Or,{size:s});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return v;switch(u.iconType){case"starting":case"capturing":return v;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(fr,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(ei,{...b});default:return v}};return n(ae,{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()})})}const _t=70;function ph({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:o,cacheBuster:s,activeTab:i,entityType:l,entity:d,queueState:m,processIsRunning:u,isEntityAnalyzing:h,areScenariosStale:p,viewMode:f,setViewMode:g,isBreakdownView:y}){var _,I,O,V,R,F;const x=Se(null),[b,v]=M(new Set),[w,C]=M(!1);ne(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const E=L=>`/entity/${o}/scenarios/${L}`,S=L=>{v(G=>{const j=new Set(G);return j.has(L)?j.delete(L):j.add(L),j})},A=(L,G=2)=>{const N=L.split(`
|
|
213
|
+
`).slice(0,G).join(" ").trim();return N.length>_t?N.substring(0,_t-3):(L.split(`
|
|
214
|
+
`).length>G||L.length>N.length,N)},k=oe(()=>{var G;if(!((G=r==null?void 0:r.metadata)!=null&&G.executionFlows)||!(r!=null&&r.scenarios))return null;const L=r.scenarios.filter(j=>{var N;return!((N=j.metadata)!=null&&N.sameAsDefault)});return Dr(r.metadata.executionFlows,L)},[r]),T=(k==null?void 0:k.totalFlows)||0,$=(k==null?void 0:k.coveredFlows)||0,D=(k==null?void 0:k.coveragePercentage)||0;(_=d==null?void 0:d.metadata)!=null&&_.defaultWidth||(I=r==null?void 0:r.metadata)!=null&&I.defaultWidth;const P=(O=r==null?void 0:r.status)!=null&&O.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return c("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&c("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),c("div",{className:"grid grid-cols-2 gap-2",children:[c(ae,{to:y?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((V=e[0])==null?void 0:V.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(D),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),c(ae,{to:y?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((R=e[0])==null?void 0:R.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[$,"/",T]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),c(ae,{to:y?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((F=e[0])==null?void 0:F.id)}`:`/entity/${o}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${y?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),y?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(ae,{to:`/entity/${o}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&c("div",{className:"py-3 flex items-center justify-between",children:[c("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),P&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:P})]}),h&&(p||e.length===0)?c("div",{className:"",children:[c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((L,G)=>{const j=!y&&(a==null?void 0:a.id)===L.id,N=b.has(L.id||"");return L.id?c(ae,{to:E(L.id),ref:j?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${j?"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(Ba,{scenario:L,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${N?"":"line-clamp-1"}`,children:L.name}),L.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[N?L.description:A(L.description),!N&&L.description.length>_t&&c(ce,{children:["...",n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),S(L.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),N&&L.description.length>_t&&n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),S(L.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},G):null})})}),t.length>0&&!(h&&p)&&c("div",{className:"border-t border-[#e1e1e1] pt-3",children:[c("button",{onClick:()=>C(!w),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${w?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),w&&c("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((L,G)=>{const j=!y&&(a==null?void 0:a.id)===L.id,N=b.has(L.id||"");return L.id?c(ae,{to:`/entity/${o}/scenarios/${L.id}`,ref:j?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${j?"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(Ba,{scenario:L,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${N?"":"line-clamp-1"}`,children:L.name}),L.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[N?L.description:A(L.description),!N&&L.description.length>_t&&c(ce,{children:["...",n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),S(L.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),N&&L.description.length>_t&&n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),S(L.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},G):null})})]})]})]})}function fh({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:o,onDelete:s,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:h=!1,deleteError:p=null}){const[f,g]=M(""),y=async()=>{await r(f)},x=async b=>{await a(f,b),b||g("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(ae,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:b=>g(b.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),c("button",{onClick:()=>void y(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&c("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),c("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:o,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(ae,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),s&&c(ce,{children:[m?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void s(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function gh({scenario:e,analysis:t,entity:r}){var i,l,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,o=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],s=m=>{var g,y,x;if(!m)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],h=((g=m.sideEffects)==null?void 0:g.consoleOutput)||[];h.length>0&&(u.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(b=>{u.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const p=((y=m.sideEffects)==null?void 0:y.fileWrites)||[];p.length>0&&(u.push(`
|
|
215
|
+
File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(b=>{u.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=m.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
216
|
+
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{u.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),m.error&&u.push(`
|
|
217
|
+
Error: ${m.error.name||"Error"}: ${m.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
218
|
+
`)};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(o,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:s(a)})})]})]})}const xt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function dn({scenarioId:e,analysisId:t}){const[r,a]=M(!1),[o,s]=M(!1),[i,l]=M(null),[d,m]=M(!1),u=e||t;if(!u)return null;const h=`/codeyam:diagnose ${u}`,p=async()=>{s(!0);try{const{default:g}=await import("html2canvas-pro"),x=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),a(!0)}catch(g){console.error("Screenshot capture failed:",g),a(!0)}finally{s(!1)}},f=()=>{a(!1),l(null)};return c(ce,{children:[c("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:xt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:xt.subtext},children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:xt.commandBoxBg,borderColor:xt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:xt.commandBoxText},children:h}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(h),m(!0),setTimeout(()=>m(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":xt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(no,{size:14}):n(ro,{size:14})})]}),c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:o,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:xt.link},children:o?"capturing...":"please do so here"}),"."]})]}),n(uo,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Ua=1440,un=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],tt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function as({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:o,hasScenarios:s,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0,processIsRunning:m,queueState:u}){var K,B,Z,de,he,ye,ve,_e,Ne,Ae,Te;const h=Ee(),[p,f]=M(!1),[g,y]=M(!1),[x,b]=M({name:"Desktop",width:Ua,height:900}),[v,w]=M(Ua),[C,E]=M(1),{customSizes:S,addCustomSize:A,removeCustomSize:k}=Ho(l),T=oe(()=>[...un,...S],[S]),$=(ge,je)=>{w(ge);const ke=T.find(we=>we.width===ge&&we.height===je);b({name:(ke==null?void 0:ke.name)||"Custom",width:ge,height:je})},D=ge=>{w(ge.width),b({name:ge.name,width:ge.width,height:ge.height})},P=ge=>{A(ge,x.width,x.height??900),y(!1),b(je=>({...je,name:ge}))},_=(ge,je)=>{w(ge);const ke=T.find(we=>we.width===ge&&we.height===je);b(we=>({name:(ke==null?void 0:ke.name)||"Custom",width:ge,height:we.height}))},I=(B=(K=e==null?void 0:e.metadata)==null?void 0:K.screenshotPaths)==null?void 0:B[0],O=oe(()=>e?Fn(e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u]),V=oe(()=>{var je,ke;const ge=[];if((je=t==null?void 0:t.status)!=null&&je.errors&&t.status.errors.length>0)for(const we of t.status.errors)ge.push({source:`${we.phase} phase`,message:we.message,stack:we.stack});if((ke=t==null?void 0:t.status)!=null&&ke.steps)for(const we of t.status.steps)we.error&&ge.push({source:we.name,message:we.error,stack:we.errorStack});return ge},[(Z=t==null?void 0:t.status)==null?void 0:Z.errors,(de=t==null?void 0:t.status)==null?void 0:de.steps]),R=(O==null?void 0:O.errorMessage)||null,F=(O==null?void 0:O.errorStack)||null,{interactiveServerUrl:L,isStarting:G,isLoading:j,showIframe:N,iframeKey:z,onIframeLoad:W}=en({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:a==="interactive"}),H=oe(()=>L||null,[L]),re=!i&&s&&e&&!((ye=(he=e.metadata)==null?void 0:he.screenshotPaths)!=null&&ye[0])&&((_e=(ve=t==null?void 0:t.status)==null?void 0:ve.scenarios)==null?void 0:_e.some(ge=>ge.name===e.name&&ge.screenshotStartedAt&&!ge.screenshotFinishedAt)),{lastLine:J}=ht(l,i||a==="interactive"||re||!1);if(!e){if(i&&r)return c(ce,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:re?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),J&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:J}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&l&&n(dt,{projectSlug:l,onClose:()=>f(!1)})]});if(!s&&r&&!i){if(V.length>0){const ge=V.length===1?((Ne=V[0])==null?void 0:Ne.message)||"An error occurred during analysis.":`${V.length} errors occurred during analysis.`;return c(ce,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(fr,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ge," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(dn,{analysisId:t==null?void 0:t.id})})]})}),p&&l&&n(dt,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(ce,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
219
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
220
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
221
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
222
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
223
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||re&&!I)&&!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:re?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:re?`Taking screenshots for ${((Ae=t==null?void 0:t.scenarios)==null?void 0:Ae.length)||0} scenario${((Te=t==null?void 0:t.scenarios)==null?void 0:Te.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),J&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:J,children:J})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&(I||R)||a==="interactive"&&(H||G)||a==="data"?c(ce,{children:[R&&!I&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`,maxHeight:"50vh"},role:"alert",children:c("div",{className:"flex flex-col gap-3",children:[c("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:tt.text},children:[n(fr,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),c("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:R})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(dn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[H&&c("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(xd,{presets:[...un],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:C,onSizeChange:$,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:k}),e&&r&&c(ae,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),H&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${un[un.length-1].width}px`,width:"100%"},children:n(Uo,{currentViewportWidth:v,currentPresetName:x.name,onDevicePresetClick:D,devicePresets:T})})}),n(Dn,{scenarioId:e.id,scenarioName:e.name,iframeUrl:H,isStarting:G,isLoading:j,showIframe:N,iframeKey:z,onIframeLoad:W,onScaleChange:E,onDimensionChange:_,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(gh,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${v}px`},children:(I||!R)&&n(De,{screenshotPath:I,cacheBuster:o,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!I?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),J&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:J})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):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(ae,{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})})]}),F&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:F})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(dn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):V.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:V,title:"Analysis Error",description:V.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${V.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(dn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&l&&n(dt,{projectSlug:l,onClose:()=>f(!1)}),g&&n(Wo,{width:x.width,height:x.height??900,onSave:P,onCancel:()=>y(!1)})]})}function yh({analysis:e,entitySha:t}){nt();const[r,a]=M(e);ne(()=>{a(e)},[e]);const[o,s]=M(null),i=oe(()=>{var h;if(!((h=r==null?void 0:r.metadata)!=null&&h.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return Dr(r.metadata.executionFlows,u)},[r]),l=oe(()=>i?Dd(i):[],[i]),d=oe(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var h;return!((h=u.metadata)!=null&&h.sameAsDefault)}):[],[r]),m=u=>{var p;const h=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>h.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:c("div",{className:"p-6 space-y-6",children:[c("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),c("div",{className:"grid grid-cols-4 gap-4 text-center",children:[c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?c("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(ae,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,g,y;const h=(g=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0],p=m(u);return c("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(De,{screenshotPath:h,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:c("div",{children:[n(ae,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((y=u.metadata)==null?void 0:y.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:c(ae,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),l.length>0&&c("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[c("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[l.length," uncovered execution flow",l.length>1?"s":""," — consider adding scenarios to cover these"]}),c("div",{className:"flex flex-wrap gap-1",children:[l.slice(0,10).map(u=>c("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),l.length>10&&c("span",{className:"text-xs text-amber-600",children:["+",l.length-10," more"]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const h=o===u.id,p=u.usedInScenarios.length>0;return c("div",{children:[n("button",{onClick:()=>s(h?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:c("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:h?"▼":"▶"}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),h&&c("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&c("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,g)=>c("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},g))})]}),p&&c("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Wa({hasIndirectBadge:e,onAnalyze:t}){return c(ce,{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 xh({entity:e,history:t}){const[r,a]=M("entity"),[o,s]=M(new Set),i=t.filter(u=>u.analyses.length>0).length,l=oe(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(p=>{(p.scenarios??[]).filter(g=>{var y;return!((y=g.metadata)!=null&&y.sameAsDefault)}).forEach(g=>{u.has(g.name)||u.set(g.name,[]),u.get(g.name).push({version:h,analysis:p,scenario:g})})})}),Array.from(u.entries()).map(([h,p])=>{var f;return{name:h,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((g,y)=>{const x=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-x})}})},[t]),d=l.length,m=u=>{s(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==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c(ae,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var y;const g=(p.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:g.length===0?n(Wa,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):c(ce,{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:[g.length," scenario",g.length!==1?"s":""]})]})}),((y=p.metadata)==null?void 0:y.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]})}),g.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:g.map((x,b)=>{var C,E;const v=(E=(C=x.metadata)==null?void 0:C.screenshotPaths)==null?void 0:E[0],w=`${x.name}-${b}`;return c(ae,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:v?n(De,{screenshotPath:v,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},w)})})})]})},p.id||f)})}):n(Wa,{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=o.has(u.name),f=p?u.versions:u.versions.slice(0,1),g=u.versions.length-1,y=u.versions[0];return y==null||y.version.sha,e==null||e.sha,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((x,b)=>{var A,k;const{version:v,analysis:w,scenario:C}=x,E=(k=(A=C.metadata)==null?void 0:A.screenshotPaths)==null?void 0:k[0],S=b===0;return c("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(ae,{to:`/entity/${v.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:E?n(De,{screenshotPath:E,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[v.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),S&&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(ae,{to:`/entity/${v.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:v.sha.substring(0,8)})]}),w.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(w.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),w.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${b}`)}),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)})})]})})}function Ha({entity:e,analysisInfo:t,from:r}){const a=Ee(),o=a.state!=="idle",s=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),s&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(ae,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(De,{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(Ue,{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(Ue,{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(ce,{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"})]}),s&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]}):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(ce,{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"})]}),s&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const qa=e=>{var o,s,i;const t=((o=e.analysisStatus)==null?void 0:o.status)||"not_analyzed",r=((s=e.analysisStatus)==null?void 0:s.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function bh({importedEntities:e,importingEntities:t}){const[r]=Jt(),a=r.get("from"),o=Ee(),s=o.state!=="idle",i=e.length>0,l=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=p=>{const f=d(p);f.length!==0&&o.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,h=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>m(e),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(Ha,{entity:p,analysisInfo:qa(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>m(t),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(Ha,{entity:p,analysisInfo:qa(p),from:a},p.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 vh({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(bh,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function wh({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Gt,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Gt({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:o,showInlineToggle:s=!1}){const[i,l]=M(r||t<2);if(ne(()=>{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(ce,{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(Gt,{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(ce,{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(Yr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(zr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(ce,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(Gt,{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 Yr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:o}){const[s,i]=M(a||r<2),l=Object.keys(t);return ne(()=>{i(a||r<2)},[a,r]),c(ce,{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(!s),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!s&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),s&&c(ce,{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(Yr,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:o}):h?n(zr,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:o}):c(ce,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(Gt,{data:m,depth:r+2,defaultExpanded:a,maxDepth:o})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function zr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:o}){const[s,i]=M(a||r<2);return ne(()=>{i(a||r<2)},[a,r]),c(ce,{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(!s),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!s&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),s&&c(ce,{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(Yr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:o}):u?n(zr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:o}):n(Gt,{data:l,depth:r+2,defaultExpanded:a,maxDepth:o})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function ar({label:e,count:t,isActive:r,onClick:a,badgeColorActive:o,badgeTextActive:s}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${o} ${s}`:"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 Ga({label:e,isActive:t,onClick:r,disabled:a=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Ja({call:e,scenarioName:t}){const[r,a]=M(!1),[o,s]=M("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=oe(()=>{var p,f,g,y,x;try{const b=JSON.parse(e.response);return(g=(f=(p=b.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&g.content?b.choices[0].message.content:(x=(y=b.content)==null?void 0:y[0])!=null&&x.text?b.content[0].text:e.response}catch{return e.response}},[e.response]),u=oe(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=oe(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.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.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>s("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>s("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>s("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>s("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),o&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="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"})}),o==="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})}),o==="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})]}),o==="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&&!o&&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 Va=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Ch({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:o}){var w,C,E,S,A,k,T,$,D;const[s,i]=M("entity"),[l,d]=M("analysis"),[m,u]=M(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=oe(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const P=[...o.entityCalls,...o.analysisCalls],_=P.filter(O=>O.object_type==="entity"||Va.includes(O.prompt_type)),I=P.filter(O=>O.object_type!=="entity"&&!Va.includes(O.prompt_type));return _.sort((O,V)=>V.created_at-O.created_at),I.sort((O,V)=>V.created_at-O.created_at),{entityLlmCalls:_,scenarioLlmCalls:I,totalLlmCalls:P.length}},[o]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(w=e==null?void 0:e.metadata)==null?void 0:w.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(C=t==null?void 0:t.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(S=(E=e==null?void 0:e.metadata)==null?void 0:E.isolatedDataStructure)==null?void 0:S.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(A=t==null?void 0:t.metadata)==null?void 0:A.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(k=e==null?void 0:e.metadata)==null?void 0:k.importedExports,"External Dependencies":(T=e==null?void 0:e.metadata)==null?void 0:T.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:($=t==null?void 0:t.metadata)==null?void 0:$.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter(P=>P.data!==void 0&&P.data!==null).length;let v=null;if(s==="entity"){const P=x.find(_=>_.id===l);P&&P.data!==void 0&&P.data!==null&&(v={title:P.title,description:P.description,data:P.data})}else if(s==="scenarios"&&m){const P=r.find(_=>(_.id||_.name)===m.scenarioId);P&&(v={title:P.name,description:P.description||"Scenario data and configuration",data:P.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(ar,{label:"Entity",isActive:s==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(ar,{label:"Scenarios",count:r.length,isActive:s==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(ar,{label:"LLM Calls",count:y,isActive:s==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((D=t==null?void 0:t.metadata)==null?void 0:D.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})]})]})}),s==="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 cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",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(P=>n(Ja,{call:P},P.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(P=>n(Ja,{call:P},P.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:s==="entity"?c(ce,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(P=>{const _=P.data!==void 0&&P.data!==null;return n(Ga,{label:P.title,isActive:l===P.id,onClick:()=>d(P.id),disabled:!_},P.id)})})]}):c(ce,{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(P=>{const _=P.id||P.name,I=(m==null?void 0:m.scenarioId)===_;return n(Ga,{label:P.name,isActive:I,onClick:()=>u({scenarioId:_})},_)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(Nh,{title:v.title,description:v.description,data:v.data}):s==="scenarios"&&r.length===0?n(Qa,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):s==="entity"?n(Qa,{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 Qa({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 Nh({title:e,description:t,data:r}){const[a,o]=M(!0),[s,i]=M("Copy JSON");return c(ce,{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:()=>o(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>o(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),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:s})]}),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(wh,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Sh({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const o=Ee();return ne(()=>{if(e!=null&&e.sha&&o.state==="idle"&&!o.data){const s=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;o.load(s)}},[e==null?void 0:e.sha,t==null?void 0:t.id,o.state,o.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(Ch,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:o.data})})}function Eh({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:o=2e3,ariaLabel:s}){const[i,l]=M(!1),d=se(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),o)}).catch(m=>{console.error("Failed to copy:",m)})},[e,o]);return n("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":s||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?r:t})}const Ah={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},kh={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Ph=2e3,Mh=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function _h({entity:e,entityCode:t}){const r=En(),a=Se(null);return ne(()=>{const o=r.hash;if(!o||!a.current)return;const s=o.match(/^#L(\d+)$/);if(!s)return;const i=parseInt(s[1],10);setTimeout(()=>{if(!a.current)return;const l=a.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const d=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:a,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(Eh,{content:t,label:"Copy Code",duration:Ph,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(Li,{language:Mh(e==null?void 0:e.filePath),style:Fi,showLineNumbers:!0,customStyle:Ah,lineNumberStyle:kh,wrapLines:!0,lineProps:o=>({"data-line-number":o,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Th=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Ih({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:o,defaultShouldRevalidate:s}){return r.pathname===a.pathname&&r.search===a.search?s:!!(e.sha!==t.sha||o)}async function $h({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const s=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,x]=await Promise.all([At(a),Ye(),Mt(),mc(me()||process.cwd())]),b=f?await _r(f):null,v=f?await Ao(f.sha):null;let w={importedEntities:[],importingEntities:[]},C=null,E=[];f&&(w=await ko(f),C=await Po(f),E=await _o(f));const S=!!(f&&E.length>0&&E[0].sha!==f.sha),A=E.length>0?E[0].sha:null,k=!!(E.length>0&&E[0].analyses&&E[0].analyses.length>0),T=f?await Mo(f):!1;return U({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:v??void 0,projectSlug:g,from:s,relatedEntities:w,entityCode:C??void 0,hasNewerVersion:S,newestEntitySha:A,newestVersionHasAnalysis:k,fileModifiedSinceEntity:T,history:E,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:x,queueState:p})}const jh=Oe(function(){var Qr,Kr,Zr,Xr,ea,ta,na,ra,aa,oa,sa,ia,la,ca,da;const t=We(),o=(eo()["*"]||"").split("/").filter(Boolean),s=o[0]||"scenarios",i=o[1]||null,l=o[2]||null,d=t.entity,m=t.analysis,u=t.currentEntityAnalysis,h=u||m,p=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,v=t.fileModifiedSinceEntity,w=t.history,C=t.currentCommit,E=t.hasAnApiKey,S=t.queueState;(Qr=h==null?void 0:h.status)==null||Qr.errors;const A=(h==null?void 0:h.scenarios)||[],k=A.filter(te=>{var ue;return!((ue=te.metadata)!=null&&ue.sameAsDefault)}),T=A.filter(te=>{var ue;return(ue=te.metadata)==null?void 0:ue.sameAsDefault}),$=It(),D=Se(null);ne(()=>{D.current===null&&(D.current=window.history.length)},[]);const P=()=>{if(typeof window>"u")return;const te=window.history.state;if(te===null||(te==null?void 0:te.idx)===void 0||(te==null?void 0:te.idx)===0)$("/");else{const ue=window.history.length,Be=D.current;if(Be!==null&&ue>Be){const Ce=ue-Be+1;$(-Ce)}else $(-1)}},_=!!S.currentlyExecuting,I=s,O=(Kr=C==null?void 0:C.metadata)==null?void 0:Kr.currentRun,V=!!(O!=null&&O.createdAt)&&!(O!=null&&O.analysisCompletedAt),R=!!(d!=null&&d.sha&&((Zr=O==null?void 0:O.currentEntityShas)!=null&&Zr.includes(d.sha))),F=!!(d!=null&&d.sha&&((ea=(Xr=S.currentlyExecuting)==null?void 0:Xr.entityShas)!=null&&ea.includes(d.sha))),L=!!(d!=null&&d.sha&&((ta=S.jobs)!=null&&ta.some(te=>{var ue;return(ue=te.entityShas)==null?void 0:ue.includes(d.sha)}))),G=R||F||L,j=G&&((na=h==null?void 0:h.status)==null?void 0:na.finishedAt)!=null&&k.length>0&&h.entitySha!==(d==null?void 0:d.sha),N=oe(()=>{if(I!=="scenarios")return null;if(i){const te=k.find(ue=>ue.id===i);if(te)return te}return k.length>0&&!G?k[0]:null},[I,i,k,G]),z=((oa=(aa=(ra=N==null?void 0:N.metadata)==null?void 0:ra.executionResult)==null?void 0:aa.error)==null?void 0:oa.message)||((la=(ia=(sa=h==null?void 0:h.status)==null?void 0:sa.errors)==null?void 0:ia[0])==null?void 0:la.message);mt({source:N?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:N==null?void 0:N.id,analysisId:h==null?void 0:h.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:N==null?void 0:N.name,errorMessage:z});const[W,H]=M(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ne(()=>{l&&l!==W&&l!=="edit"&&H(l)},[l]);const re=l==="edit",[J,Y]=M(!1),[q,K]=M(!1),[B,Z]=M(null),[de,he]=M(!1),[ye,ve]=M(!1),[_e,Ne]=M(null),[Ae,Te]=M(null),[ge,je]=M(0),{interactiveServerUrl:ke,isStarting:we,isLoading:tn,showIframe:le,iframeKey:qe,onIframeLoad:Ge}=en({analysisId:h==null?void 0:h.id,scenarioId:N==null?void 0:N.id,scenarioName:N==null?void 0:N.name,projectSlug:p,enabled:re&&!!N,refreshTrigger:ge}),[On,tf]=M(!1),[nf,rf]=M(""),[nn,Dt]=M(!1),[qr,Yn]=M(Date.now()),[us,zn]=M(!1),Xe=Ee(),gt=Ee(),ze=Ee(),Re=nt(),ms=S.jobs.some(te=>{var ue;return(d==null?void 0:d.sha)&&((ue=te.entityShas)==null?void 0:ue.includes(d.sha))||te.type==="analysis"&&te.commitSha===(C==null?void 0:C.sha)&&te.entityShas&&te.entityShas.length===0}),Bn=G,Gr=((ca=d==null?void 0:d.metadata)==null?void 0:ca.defaultWidth)||((da=h==null?void 0:h.metadata)==null?void 0:da.defaultWidth)||1440,hs=Math.round(Gr*(900/1440));Xe.state==="submitting"||Xe.state,oe(()=>{var te;return!!((te=N==null?void 0:N.metadata)!=null&&te.interactiveExamplePath)},[N]);const{isCompleted:Jr}=ht(p,nn);ne(()=>{Xe.state==="idle"&&Xe.data&&(Xe.data.success?setTimeout(()=>{Yn(Date.now()),Re.revalidate(),Dt(!1)},1500):Xe.data.error&&(Dt(!1),alert(`Recapture failed: ${Xe.data.error}`)))},[Xe.state,Xe.data,Re]),ne(()=>{nn&&Jr&&setTimeout(()=>{Yn(Date.now()),Re.revalidate(),Dt(!1)},1500)},[nn,Jr,Re]),ne(()=>{gt.state==="idle"&>.data&&(gt.data.success?setTimeout(()=>{Yn(Date.now()),Re.revalidate(),Dt(!1)},1500):gt.data.error&&(Dt(!1),alert(`Recapture failed: ${gt.data.error}`)))},[gt.state,gt.data,Re]);const Vr=()=>{d&&(y&&x&&x!==d.sha?($(`/entity/${x}/scenarios`),setTimeout(()=>{ze.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):ze.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ne(()=>{ze.state==="idle"&&ze.data&&(ze.data.success?Re.revalidate():ze.data.error&&alert(`Analysis failed: ${ze.data.error}`))},[ze.state,ze.data,d==null?void 0:d.sha,Re]),ne(()=>{const te=setTimeout(()=>{Re.revalidate()},500);return()=>clearTimeout(te)},[]),ne(()=>{if(V||Bn){const te=setInterval(()=>{Re.revalidate()},3e3);return()=>clearInterval(te)}else{const te=setInterval(()=>{Re.revalidate()},5e3),ue=setTimeout(()=>{clearInterval(te)},3e4);return()=>{clearInterval(te),clearTimeout(ue)}}},[V,Bn,Re]);const ps=(te,ue)=>te==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${te}`,fs=(te,ue)=>`/entity/${d==null?void 0:d.sha}/scenarios/${te}/${ue}`,gs=te=>{H(te),N!=null&&N.id&&(te==="interactive"?$(`/entity/${d==null?void 0:d.sha}/scenarios/${N.id}/fullscreen`,{replace:!0}):$(fs(N.id,te),{replace:!0}))},ys=async te=>{var ue,Be;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:te,hasSelectedScenario:!!N,hasAnalysis:!!h}),!N||!h){const Ce="Error: No scenario or analysis available";console.error("[EntityDetail]",Ce),Z(Ce);return}Y(!0),Z(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:te,scenarioId:N.id,scenarioName:N.name,currentData:N.data});try{const Ce=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:te,existingScenarios:h.scenarios,scenariosDataStructure:(ue=h.metadata)==null?void 0:ue.scenariosDataStructure,editingMockName:N.name,editingMockData:Ae||((Be=N.metadata)==null?void 0:Be.data)})}),et=await Ce.json();if(!Ce.ok||!et.success)throw new Error(et.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",et.data),Te(et.data);const rn=(h.scenarios||[]).map(Le=>Le.id===N.id?{...Le,metadata:{...Le.metadata,data:et.data}}:Le),Lt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:rn})}),Je=await Lt.json();if(!Lt.ok||!Je.success)throw console.error("[EntityDetail] Temp save failed:",Je),new Error(Je.error||"Failed to apply preview");if(Z("Generating preview. Capturing screenshot..."),ke){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ke});const Le=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ke,scenarioId:N.id,projectId:h.projectId,viewportWidth:1440})}),Ft=await Le.json();!Le.ok||!Ft.success?(console.error("[EntityDetail] Direct capture failed:",Ft),Z("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),Z('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Le=new FormData;Le.append("analysisId",h.id||""),Le.append("scenarioId",N.id||"");const Ft=await fetch("/api/recapture-scenario",{method:"POST",body:Le}),Wn=await Ft.json();!Ft.ok||!Wn.success?(console.warn("[EntityDetail] Recapture failed:",Wn.error),Z("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Wn.jobId),Z('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}je(Le=>Le+1),Re.revalidate()}catch(Ce){console.error("Error applying changes:",Ce),Z(`Error: ${Ce instanceof Error?Ce.message:String(Ce)}`)}finally{Y(!1)}},xs=async(te,ue)=>{var Be;if(!N||!h){Z("Error: No scenario or analysis available");return}K(!0),Z(null),console.log("[EntityDetail] Saving scenario to database",{description:te,saveAsNew:ue});try{const Ce=Ae||((Be=N.metadata)==null?void 0:Be.data);let et;if(ue){const Je={...N,id:`${N.name}-${Date.now()}`,name:`${N.name} (Copy)`,metadata:{...N.metadata,data:Ce},description:te||N.description};et=[...h.scenarios||[],Je]}else et=(h.scenarios||[]).map(Je=>Je.id===N.id?{...Je,metadata:{...Je.metadata,data:Ce},description:te||Je.description}:Je);const rn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:et})}),Lt=await rn.json();if(!rn.ok||!Lt.success)throw new Error(Lt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),Z(ue?"New scenario created successfully":"Scenario saved successfully"),Te(null),Re.revalidate()}catch(Ce){console.error("Error saving scenario:",Ce),Z(`Error: ${Ce instanceof Error?Ce.message:String(Ce)}`)}finally{K(!1)}},bs=()=>{console.log("[EntityDetail] Edit mock data clicked"),Z("Mock data editor coming soon")},vs=async()=>{var te;if(!(N!=null&&N.id)){Ne("Cannot delete scenario without ID");return}he(!0),Ne(null);try{const ue=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:N.id,screenshotPaths:((te=N.metadata)==null?void 0:te.screenshotPaths)||[]})}),Be=await ue.json();if(!ue.ok||!Be.success)throw new Error(Be.error||"Failed to delete scenario");$(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(ue){console.error("[EntityDetail] Error deleting scenario:",ue),Ne(ue instanceof Error?ue.message:"Failed to delete scenario"),ve(!1)}finally{he(!1)}},Un=h&&d&&h.entitySha!==d.sha,ws=d?hh(d):!1;return n(Rn,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:P,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:k.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(te=>n(ae,{to:ps(te.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${I===te.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:I===te.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[te.label,te.count!==void 0&&te.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${I===te.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:te.count})]})},te.id))})]})}),(y||Un&&!u||v&&ws)&&!G&&!ms&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:c("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Un&&!y?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:y?"You are viewing an older version. A newer version is available.":Un?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),y&&x&&b?n(ae,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:te=>{te.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:te=>{te.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Vr,disabled:ze.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:te=>{ze.state==="idle"&&(te.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:te=>{ze.state==="idle"&&(te.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[I==="scenarios"&&c(ce,{children:[re&&N?n(fh,{scenario:N,entitySha:(d==null?void 0:d.sha)||"",onApply:ys,onSave:xs,onEditMockData:bs,onDelete:vs,isApplying:J,isSaving:q,saveMessage:B,showDeleteConfirm:ye,onShowDeleteConfirm:ve,isDeleting:de,deleteError:_e}):n(ph,{scenarios:k,hiddenScenarios:T,analysis:h,selectedScenario:N,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:qr,activeTab:I,entityType:d==null?void 0:d.entityType,entity:d,queueState:S,processIsRunning:_,isEntityAnalyzing:G,areScenariosStale:j,viewMode:W,setViewMode:gs,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(yh,{analysis:h??null,entitySha:(d==null?void 0:d.sha)||""}):re&&N?n(Dn,{scenarioId:N.id||N.name,scenarioName:N.name,iframeUrl:ke,isStarting:we,isLoading:tn,showIframe:le,iframeKey:qe,onIframeLoad:Ge,projectSlug:p,defaultWidth:1440,defaultHeight:900}):c("div",{className:"flex flex-col flex-1 min-h-0",children:[N&&c("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:N.name}),c("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Gr," × ",hs]})]}),c("div",{className:"flex items-center gap-2",children:[n(ae,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${N.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),c("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),c(ae,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${N.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(as,{selectedScenario:N,analysis:h,entity:d,viewMode:W,cacheBuster:qr,hasScenarios:k.length>0,isAnalyzing:Bn,projectSlug:p,hasAnApiKey:E,processIsRunning:_,queueState:S})]})]}),I==="related"&&n(vh,{relatedEntities:f}),I==="data"&&n(Sh,{entity:d,analysis:h,scenarios:k,onAnalyze:Vr}),I==="code"&&n(_h,{entity:d,entityCode:g}),I==="history"&&n(xh,{entity:d,history:w})]}),us&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>zn(!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:te=>te.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:()=>zn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(dt,{projectSlug:p,onClose:()=>zn(!1)})})]})})]})})}),Rh=Object.freeze(Object.defineProperty({__proto__:null,default:jh,loader:$h,meta:Th,shouldRevalidate:Ih},Symbol.toStringTag,{value:"Module"}));async function Dh(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:o,queue:s}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await $e();const i=me();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=pe.join(i,".codeyam","config.json"),d=JSON.parse(await xe.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=$n(m);try{await xe.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Fe(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await Et({shas:t});if(!g||g.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let y=r;if((!y||y.length===0)&&(y=[...new Set(g.map(v=>v.filePath).filter(v=>!!v))],console.log(`[analyzeEntities] Found ${y.length} unique files`)),!y||y.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${y.length} files...`);const x=await cc(p,f,y);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ct({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(v,w)=>{if(!v)return;const C=v.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&xc(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=s.enqueue({type:"analysis",commitSha:x.sha,projectSlug:m,filePaths:y,entityShas:t,entityNames:g.map(v=>v.name),...a?{context:a}:{},...o?{scenarioCount:o}:{}});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 Lh({request:e,context:t}){if(e.method!=="POST")return U({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await st()),!r)return U({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("entitySha"),s=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let m;if(s)m=s.split(",").filter(Boolean);else if(o)m=[o];else return U({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return U({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await Et({shas:m}),p=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await Dh({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: ${f}`),U({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),U({error:"Failed to start analysis",details:a.message},{status:500})}}const Fh=Object.freeze(Object.defineProperty({__proto__:null,action:Lh},Symbol.toStringTag,{value:"Module"}));function Oh(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function os(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const o=t.getHours(),s=t.getMinutes(),i=o>=12?"pm":"am",l=o%12||12,d=s.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Ve(e,t=[],r=!1){var u,h;if(t.some(p=>{var f,g;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(g=p.entities)!=null&&g.some(y=>y.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const o=e.analyses[0];if(!(((u=o.status)==null?void 0:u.scenarios)&&o.status.scenarios.length>0&&o.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||o.entitySha!==e.sha)return"not-analyzed";const i=o.createdAt?new Date(o.createdAt).getTime():0,l=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,d=o.scenarios||[],m=d.some(p=>{var f,g,y;return((g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||((y=p.metadata)==null?void 0:y.executionResult)});return i>=l?d.length>0&&m?d.every(f=>{var g,y,x;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Yh=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function zh({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},o=await Zt();return U({entities:o||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),U({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Bh=Oe(function(){const t=We(),r=t.entities,a=t.queueState;mt({source:"simulations-page"});const[o,s]=M(""),[i,l]=M("visual"),d=oe(()=>{const y=[];return r.forEach(x=>{var v;const b=(v=x.analyses)==null?void 0:v[0];if(b!=null&&b.scenarios){const w=b.scenarios.filter(C=>{var E;return!((E=C.metadata)!=null&&E.sameAsDefault)}).map(C=>{var D,P,_,I,O;const E=(P=(D=C.metadata)==null?void 0:D.screenshotPaths)==null?void 0:P[0],S=(_=C.metadata)==null?void 0:_.noScreenshotSaved,A=E&&!S,k=(O=(I=b.status)==null?void 0:I.scenarios)==null?void 0:O.find(V=>V.name===C.name),T=k&&k.screenshotStartedAt&&!k.screenshotFinishedAt;let $;return A?$="completed":T?$="capturing":$="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:E||"",scenarioId:C.id,state:$}}).filter(C=>C.state==="completed"||C.state==="capturing");w.length>0&&y.push({entity:x,screenshots:w,createdAt:b.createdAt||""})}}),y.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),y},[r]),m=oe(()=>r.filter(y=>{var v,w;const x=(v=y.analyses)==null?void 0:v[0];return!((w=x==null?void 0:x.scenarios)==null?void 0:w.some(C=>{var E,S;return(S=(E=C.metadata)==null?void 0:E.screenshotPaths)==null?void 0:S[0]}))}),[r]),u=oe(()=>d.filter(({entity:y})=>{const x=!o||y.name.toLowerCase().includes(o.toLowerCase()),b=i==="all"||y.entityType===i;return x&&b}),[d,o,i]),h=oe(()=>m.filter(y=>{const x=!o||y.name.toLowerCase().includes(o.toLowerCase()),b=i==="all"||y.entityType===i;return x&&b}),[m,o,i]),p=se(y=>{s(y.target.value)},[]),f=se(y=>{l(y.target.value)},[]),g=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:c("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(oo,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:o,onChange:p})]})]})]}),g&&u.length>0&&n("div",{className:"mb-2",children:c("div",{className:"flex items-center py-3",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((y,{screenshots:x})=>y+x.length,0)})," ","scenarios"]})]})}),c("div",{className:"flex flex-col gap-3",children:[g&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ce,{children:u.map(({entity:y,screenshots:x})=>n(Uh,{entity:y,screenshots:x,queueJobs:(a==null?void 0:a.jobs)||[]},y.sha))})),!g&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(y=>n(Wh,{entity:y},y.sha)))]})]})})});function Uh({entity:e,screenshots:t,queueJobs:r}){var f,g,y;const a=It(),o=Ee(),[s,i]=M(!1),l=t.length||(((y=(g=(f=e.analyses)==null?void 0:f[0])==null?void 0:g.scenarios)==null?void 0:y.length)??0),d=x=>{a(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},m=()=>{i(!0),o.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ne(()=>{o.state==="idle"&&s&&i(!1)},[o.state,s]);const u=Ve(e,r),h=Oh(u),p=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:c("div",{className:"flex flex-col",children:[c("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(Ue,{type:e.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[c(ae,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),c("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(ce,{children:s||o.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:m,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>c("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(De,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Or,{size:"medium"}):null})}),c("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:c("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&c(ce,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Wh({entity:e}){const t=Ee(),[r,a]=M(!1),o=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ne(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:o,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(Ue,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(ae,{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:os(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:o,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const Hh=Object.freeze(Object.defineProperty({__proto__:null,default:Bh,loader:zh,meta:Yh},Symbol.toStringTag,{value:"Module"}));function qh({request:e,context:t}){const r=t.dbNotifier||cr;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(o){const s=new TextEncoder;o.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
224
|
+
|
|
225
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{o.close()}catch{}}},d=u=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
226
|
+
|
|
227
|
+
`))}catch{l()}};r.on("change",d);const m=setInterval(()=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
228
|
+
|
|
229
|
+
`))}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 Gh=Object.freeze(Object.defineProperty({__proto__:null,loader:qh},Symbol.toStringTag,{value:"Module"}));function Jh(){return new Response(JSON.stringify({status:"ok",version:jr,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const Vh=Object.freeze(Object.defineProperty({__proto__:null,loader:Jh},Symbol.toStringTag,{value:"Module"}));function wt(){const e=process.memoryUsage(),t=Yi.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(lr.totalmem()/1024/1024),freeMemory:Math.round(lr.freemem()/1024/1024)}}}function Qh(){const e=wt();console.log(`
|
|
230
|
+
[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 Kh(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=wt();global.gc();const t=wt(),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 Zh(){const e=wt(),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 Xh({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=Kh(),o=wt();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:o})}case"detailed":{const a=Qh();return Response.json({success:!0,stats:a})}case"leaks":{const a=Zh(),o=wt();return Response.json({success:!0,leakCheck:a,stats:o})}default:{const a=wt();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 ep=Object.freeze(Object.defineProperty({__proto__:null,loader:Xh},Symbol.toStringTag,{value:"Module"}));async function tp({request:e,context:t}){var s;let r=t.analysisQueue;if(r||(r=await st()),!r)return U({error:"Queue not initialized"},{status:500});const a=new URL(e.url),o=a.searchParams.get("queryType");if(!o)return U({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const i=a.searchParams.get("jobId");if(!i)return U({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((s=l.currentlyExecuting)==null?void 0:s.id)===i)return U({jobId:i,status:"running",job:l.currentlyExecuting});const d=l.jobs.find(u=>u.id===i);if(d){const u=l.jobs.indexOf(d);return U({jobId:i,status:"queued",position:u,job:d})}const m=r.getJobResult(i);return m?U({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):U({jobId:i,status:"completed"})}if(o==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>At(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}return{id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}));let d;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>At(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}d={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return U({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return U({error:"Unknown queryType"},{status:400})}async function np({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await st(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),U({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:o,...s}=a;if(console.log("[Queue API] Action:",o,"Params:",Object.keys(s)),o==="enqueue"){const{jobId:i,completion:l}=r.enqueue(s);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),U({jobId:i,status:"queued"})}if(o==="resume")return r.resume(),U({status:"resumed"});if(o==="pause")return r.pause(),U({status:"paused"});if(o==="remove"){const{jobId:i}=s;return i?r.removeJob(i)?U({status:"removed",jobId:i}):U({error:"Job not found in queue"},{status:404}):U({error:"Missing jobId parameter"},{status:400})}if(o==="clear"){const i=r.clearQueue();return U({status:"cleared",count:i})}if(o==="reorder"){const{jobId:i,direction:l}=s;return!i||!l?U({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?U({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?U({status:"reordered",jobId:i,direction:l}):U({error:"Could not reorder job (not found or at boundary)"},{status:400})}return U({error:"Unknown action"},{status:400})}const rp=Object.freeze(Object.defineProperty({__proto__:null,action:np,loader:tp},Symbol.toStringTag,{value:"Module"}));function ap(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const a=r[1],o=r[2],s={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);i&&(s.paths=i[1].split(`
|
|
231
|
+
`).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean));const l=a.match(/category:\s*([^\n]+)/);if(l){const m=l[1].trim().replace(/['"]/g,"");(m==="architecture"||m==="testing"||m==="faq")&&(s.category=m)}const d=a.match(/timestamp:\s*([^\n]+)/);return d&&(s.timestamp=d[1].trim().replace(/['"]/g,"")),{frontmatter:s,body:o}}async function ss(e,t=""){const r=[];try{const a=await xe.readdir(e,{withFileTypes:!0});for(const o of a){const s=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){const i=await ss(pe.join(e,o.name),s);r.push(...i)}else o.isFile()&&o.name.endsWith(".md")&&r.push(s)}}catch{}return r}async function op({request:e}){const t=me();if(!t)return Response.json({error:"Project root not found"},{status:500});if(new URL(e.url).searchParams.get("action")==="recent-changes")return ip(t);const o=pe.join(t,".claude","rules");try{const s=await ss(o),i=[];for(const l of s){const d=pe.join(o,l);try{const m=await xe.readFile(d,"utf-8"),u=await xe.stat(d),{frontmatter:h,body:p}=ap(m);i.push({filePath:l,content:m,frontmatter:h,body:p,lastModified:u.mtime.toISOString()})}catch{}}return i.sort((l,d)=>new Date(d.lastModified).getTime()-new Date(l.lastModified).getTime()),Response.json({rules:i})}catch(s){return console.error("[API] Error loading rules:",s),Response.json({error:"Failed to load rules",details:s instanceof Error?s.message:String(s)},{status:500})}}async function sp(e,t){const r=[];try{const a=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const o of a.split(`
|
|
232
|
+
`).filter(Boolean)){const s=o.substring(0,2);let i=o.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=i.replace(".claude/rules/","");let d="modified";const m=s[0],u=s[1];m==="A"||m==="?"?d="added":m==="D"||u==="D"?d="deleted":(m==="M"||u==="M")&&(d="modified");let h="";try{if(d==="deleted")h=t(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(d==="added"&&m==="?"){const p=`${e}/${i}`;try{const f=await xe.readFile(p,"utf-8");h=`diff --git a/${i} b/${i}
|
|
233
|
+
new file mode 100644
|
|
234
|
+
--- /dev/null
|
|
235
|
+
+++ b/${i}
|
|
236
|
+
@@ -0,0 +1,${f.split(`
|
|
237
|
+
`).length} @@
|
|
238
|
+
${f.split(`
|
|
239
|
+
`).map(g=>"+"+g).join(`
|
|
240
|
+
`)}`}catch{h="(content not available)"}}else h=t(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});h.length>5e3&&(h=h.substring(0,5e3)+`
|
|
241
|
+
... (truncated)`)}catch{h="(diff not available)"}r.push({filePath:l,changeType:d,diff:h})}}catch{}return r}async function ip(e){try{const{execSync:t}=await import("child_process"),r=[],a=await sp(e,t);a.length>0&&r.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:a});const s=t('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
|
|
242
|
+
`).filter(Boolean).slice(0,20);for(const i of s){const[l,d,...m]=i.split("|"),u=m.join("|");if(!l||!d)continue;const h=t(`git diff-tree --no-commit-id --name-status -r ${l} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),p=[];for(const f of h.split(`
|
|
243
|
+
`).filter(Boolean)){const[g,y]=f.split(" ");if(!y||!y.startsWith(".claude/rules/"))continue;const x=y.replace(".claude/rules/","");let b="modified";g==="A"?b="added":g==="D"&&(b="deleted");let v="";try{v=t(`git show ${l} --format="" -- "${y}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),v.length>5e3&&(v=v.substring(0,5e3)+`
|
|
244
|
+
... (truncated)`)}catch{v="(diff not available)"}p.push({filePath:x,changeType:b,diff:v})}p.length>0&&r.push({commitHash:l.substring(0,8),date:d,message:u,files:p})}return Response.json({changes:r})}catch(t){return console.error("[API] Error getting recent changes:",t),Response.json({changes:[]})}}async function lp({request:e}){const t=me();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=pe.join(t,".claude","rules");try{const a=await e.json(),{action:o,filePath:s,content:i}=a;if(!s)return Response.json({error:"Missing required field: filePath"},{status:400});const l=pe.normalize(s);if(l.includes("..")||pe.isAbsolute(l))return Response.json({error:"Invalid file path"},{status:400});const d=pe.join(r,l);switch(o){case"create":case"update":return i?(await xe.mkdir(pe.dirname(d),{recursive:!0}),await xe.writeFile(d,i,"utf-8"),console.log(`[API] Rule ${o}d: ${s}`),Response.json({success:!0,message:`Rule ${o}d successfully`,filePath:s})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await xe.unlink(d),console.log(`[API] Rule deleted: ${s}`);const m=pe.dirname(d);try{(await xe.readdir(m)).length===0&&m!==r&&await xe.rmdir(m)}catch{}return Response.json({success:!0,message:"Rule deleted successfully"})}catch(m){if(m.code==="ENOENT")return Response.json({error:"Rule not found"},{status:404});throw m}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(a){return console.error("[API] Error managing rule:",a),Response.json({error:"Failed to manage rule",details:a instanceof Error?a.message:String(a)},{status:500})}}const cp=Object.freeze(Object.defineProperty({__proto__:null,action:lp,loader:op},Symbol.toStringTag,{value:"Module"})),dp=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],up=Oe(function(){return Ee(),n(Rn,{children:c("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(as,{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})]})]})})}),mp=Object.freeze(Object.defineProperty({__proto__:null,default:up,meta:dp},Symbol.toStringTag,{value:"Module"})),hp=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function pp({request:e}){try{const t=await Tr();if(!t)return U({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=me()||process.cwd(),a=await In(r),o=Yo(t.projectSlug);return U({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:o,error:null})}catch(t){return console.error("Failed to load config:",t),U({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function fp(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],a=t.length>1?t.slice(1):void 0;return{command:r,args:a}}async function gp({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),o=t.get("groqApiKey"),s=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore");let d;if(r)try{d=JSON.parse(r)}catch{return U({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let m;if(a)try{m=JSON.parse(a)}catch{return U({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let u;l&&(u=l.split(",").map(g=>g.trim()).map(g=>g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")?g.slice(1,-1):g).filter(g=>g.length>0));let h;if(m){const g=await Tr();g!=null&&g.webapps&&(h=g.webapps.map((y,x)=>{if(m[x]!==void 0){const b=fp(m[x]);return{...y,startCommand:b}}return y}))}if(!await To({universalMocks:d,pathsToIgnore:u,webapps:h}))return U({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(o!==void 0||s!==void 0||i!==void 0){const g=me()||process.cwd(),y=await In(g);f=o!==void 0&&o!==(y.GROQ_API_KEY||"")||s!==void 0&&s!==(y.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(y.OPENAI_API_KEY||""),await uc(g,{...y,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:i||void 0},!0)}return U({success:!0,error:null,requiresRestart:f})}catch(t){return console.log("[Settings Action] Failed to save config:",t),U({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Ka(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Za({mock:e,onSave:t,onCancel:r}){const[a,o]=M(e.entityName),[s,i]=M(e.filePath),[l,d]=M(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=>o(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:s,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),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-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!s.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:s,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function yp(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const xp=Oe(function(){var q,K;const{config:t,secrets:r,versionInfo:a,error:o}=We(),s=$s(),i=Ee(),l=nt(),[d,m]=M("project-metadata");mt({source:"settings-page"});const[u,h]=M((t==null?void 0:t.universalMocks)||[]),[p,f]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,y]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[x,b]=M((r==null?void 0:r.GROQ_API_KEY)||""),[v,w]=M((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,E]=M((r==null?void 0:r.OPENAI_API_KEY)||""),[S,A]=M(!1),[k,T]=M(!1),[$,D]=M(!1),[P,_]=M(!1),[I,O]=M(!1),[V,R]=M(!1),[F,L]=M(null),[G,j]=M(!1),[N,z]=M({});ne(()=>{var B;if(t){h(t.universalMocks||[]);const Z=(t.pathsToIgnore||[]).join(", ");f(Z),y(Z);const de={};(B=t.webapps)==null||B.forEach((he,ye)=>{he.startCommand&&(de[ye]=Ka(he.startCommand))}),z(de)}r&&(b(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),E(r.OPENAI_API_KEY||""))},[t,r]),ne(()=>{if(s!=null&&s.success){_(!0);const B=setTimeout(()=>_(!1),3e3);return()=>clearTimeout(B)}},[s]),ne(()=>{if(i.state==="idle"&&i.data&&!V){console.log("[Settings] Fetcher data:",i.data);const B=i.data;if(B.success){console.log("[Settings] Save successful, revalidating..."),_(!0),R(!0),(p!==g||B.requiresRestart)&&O(!0),l.revalidate();const Z=setTimeout(()=>{_(!1),R(!1)},3e3);return()=>clearTimeout(Z)}}},[i.state,i.data,V,l,p,g]);const W=B=>{B.preventDefault();const Z=new FormData(B.currentTarget);Z.set("universalMocks",JSON.stringify(u)),Z.set("startCommands",JSON.stringify(N)),console.log("[Settings] Submitting form data:",{universalMocks:Z.get("universalMocks"),startCommands:Z.get("startCommands"),openAiApiKey:Z.get("openAiApiKey")?"***":"(empty)"}),i.submit(Z,{method:"post"})},H=B=>{h([...u,B]),j(!1)},re=(B,Z)=>{const de=[...u];de[B]=Z,h(de),L(null)},J=B=>{h(u.filter((Z,de)=>de!==B))};if(o)return c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const Y=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"current-configuration",label:"Current Configuration"}];return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:i.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:i.state==="submitting"?"Saving...":"Save Settings"})]}),c("div",{className:"flex gap-8 items-start",children:[n("nav",{className:"w-64 flex-shrink-0",children:n("ul",{className:"space-y-1",children:Y.map(B=>n("li",{children:n("button",{type:"button",onClick:()=>m(B.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===B.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:B.label})},B.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:W,className:"space-y-6",children:[d==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((B,Z)=>{var de;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:B.path==="."?"Root":B.path})]}),B.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:B.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:B.framework})]}),B.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[B.startCommand.command," ",(de=B.startCommand.args)==null?void 0:de.join(" ")]})]})]})},Z)})}):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`."})]})]}),d==="ai-provider"&&c("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex 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-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"groqApiKey",name:"groqApiKey",value:x,onChange:B=>b(B.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>A(!S),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:S?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex 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-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:B=>w(B.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>T(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:k?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex 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-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:$?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:B=>E(B.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>D(!$),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:$?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((B,Z)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:B.path==="."?"Root":B.path}),n("div",{className:"text-sm text-gray-600",children:B.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${Z}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${Z}`,name:`startCommand-${Z}`,value:N[Z]||"",onChange:de=>z({...N,[Z]:de.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},Z))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:p,onChange:B=>f(B.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),d==="universal-mocks"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),u.length===0?c("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>j(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:u.map((B,Z)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:F===Z?n(Za,{mock:B,onSave:de=>re(Z,de),onCancel:()=>L(null)}):n(ce,{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:B.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:B.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:B.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>L(Z),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>J(Z),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},Z))}),u.length>0&&n("button",{type:"button",onClick:()=>j(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),d==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&c("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((B,Z)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:B.path==="."?"Root":B.path})]}),B.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:B.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:B.framework})]}),B.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Ka(B.startCommand)})]})]})},Z))})]})]}),a&&c("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((q=a.templateVersion.gitCommit)==null?void 0:q.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",yp(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((K=a.cachedAnalyzerVersion.gitCommit)==null?void 0:K.slice(0,7))||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(P||I||(s==null?void 0:s.error)||i.data&&typeof i.data=="object"&&"error"in i.data)&&c("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[P&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),I&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(s==null?void 0:s.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:s.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const B=i.data;return typeof B.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:B.error}):null}return null})()]}),G&&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(Za,{mock:{entityName:"",filePath:"",content:""},onSave:H,onCancel:()=>j(!1)})]})})]})})}),bp=Object.freeze(Object.defineProperty({__proto__:null,action:gp,default:xp,loader:pp,meta:hp},Symbol.toStringTag,{value:"Module"}));async function vp({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=me();if(!r)return new Response("Project root not found",{status:500});const o=pe.extname(t)!==""?t:`${t}.html`,s=pe.join(r,".codeyam","captures","static",o);try{await xe.access(s);let i=await xe.readFile(s);const l=pe.extname(s).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 wp=Object.freeze(Object.defineProperty({__proto__:null,loader:vp},Symbol.toStringTag,{value:"Module"}));function Cp(e,t,r=10){var d;const a=new Map,o=m=>m.entityType==="visual"||m.entityType==="library";for(const m of e)o(m)&&a.set(m.sha,{entity:m,depth:0});const s=new Map;for(const m of t){const u=(d=m.metadata)==null?void 0:d.importedBy;if(u)for(const h of Object.keys(u))for(const p of Object.keys(u[h])){const{shas:f}=u[h][p];for(const g of f)s.has(m.sha)||s.set(m.sha,new Set),s.get(m.sha).add(g)}}const i=[],l=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),l.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=r)continue;const h=s.get(m);if(h)for(const p of h){if(l.has(p))continue;l.add(p);const f=t.find(g=>g.sha===p);if(f){if(o(f)){const g=u+1,y=a.get(p);(!y||g<y.depth)&&a.set(p,{entity:f,depth:g})}i.push({sha:p,depth:u+1})}}}return Array.from(a.values()).sort((m,u)=>m.depth!==u.depth?m.depth-u.depth:m.entity.name.localeCompare(u.entity.name))}function Nn(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 o=a.sort((s,i)=>{var m,u;const l=((m=s.metadata)==null?void 0:m.editedAt)||s.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(o[0])}return r}function is(e,t){const r=new Map,a=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&a.add(o.oldPath);for(const o of e){const s=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),i=s.filter(d=>{var m,u;return a.has(d.filePath)&&((m=d.metadata)==null?void 0:m.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),l=Nn(i);r.set(o.path,{status:o,entities:s,editedEntities:l})}return r}function Np(e,t,r){const a=new Map;if(!r){for(const s of e)if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const i=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),l=Nn(i);a.set(s.path,{status:s,entities:l})}return a}const o=new Map;for(const s of r.fileComparisons){const i=new Set;for(const l of s.newEntities)i.add(l.name);for(const l of s.modifiedEntities)i.add(l.name);for(const l of s.deletedEntities)i.add(l.name);i.size>0&&o.set(s.filePath,i)}for(const s of e){const i=o.get(s.path);if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const l=i?t.filter(m=>(m.filePath===s.path||s.status==="renamed"&&s.oldPath&&m.filePath===s.oldPath)&&i.has(m.name)):[],d=Nn(l);a.set(s.path,{status:s,entities:d})}}return a}function Sp(e,t){const r=new Map,a=ls(e,t);for(const o of a){const i=Cp([o],t).filter(({depth:l})=>l>0);r.set(o.sha,i)}return r}function ls(e,t){const r=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&r.add(o.oldPath);const a=t.filter(o=>{var s,i;return r.has(o.filePath)&&((s=o.metadata)==null?void 0:s.isUncommitted)&&!((i=o.metadata)!=null&&i.isSuperseded)});return Nn(a)}function Ep({recentSimulations:e}){const t=oe(()=>{const r=new Map;return e.forEach(a=>{const o=a.entitySha,s=r.get(o);s?s.push(a):r.set(o,[a])}),Array.from(r.entries()).map(([a,o])=>({entitySha:a,entityName:o[0].entityName,scenarios:o}))},[e]);return c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?c(ce,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Wt,{size:16,style:{color:"#8B5CF6"}})}),n(ae,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((a,o)=>n(ae,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:s=>{s.currentTarget.style.borderColor="#005C75",s.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:s=>{s.currentTarget.style.borderColor="#E5E7EB",s.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:n(De,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${o}`))})]},r.entitySha))}),n(ae,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):c("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Wt,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),c("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(ae,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(ae,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Ap="/assets/codeyam-name-logo-CvKwUgHo.svg",kp=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Pp({request:e,context:t}){var r,a;try{const o=t.analysisQueue,s=o?o.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([Zt(),Ye(),Mt()]),m=Zo(),u=i?is(m,i):new Map,h=Array.from(u.entries()).sort(($,D)=>$[0].localeCompare(D[0])),p=(i==null?void 0:i.length)||0,f=(i==null?void 0:i.filter($=>$.entityType==="visual").length)||0,g=(i==null?void 0:i.filter($=>$.entityType==="library").length)||0,y=i?ls(m,i):[],x=y.length,b=(i==null?void 0:i.filter($=>($.analyses??[]).filter(D=>D.scenarios&&D.scenarios.length>0).length>0).length)||0,v=(i==null?void 0:i.reduce(($,D)=>{var _,I,O;const P=((O=(I=(_=D.analyses)==null?void 0:_[0])==null?void 0:I.scenarios)==null?void 0:O.length)||0;return $+P},0))||0,w=(i==null?void 0:i.reduce(($,D)=>{var I,O;const _=(((O=(I=D.analyses)==null?void 0:I[0])==null?void 0:O.scenarios)||[]).filter(V=>{var R,F;return(F=(R=V.metadata)==null?void 0:R.screenshotPaths)==null?void 0:F[0]}).length;return $+_},0))||0,C=[];i==null||i.forEach($=>{var P;const D=(P=$.analyses)==null?void 0:P[0];D!=null&&D.scenarios&&D.scenarios.filter(I=>{var O;return!((O=I.metadata)!=null&&O.sameAsDefault)}).forEach(I=>{var V,R;const O=(R=(V=I.metadata)==null?void 0:V.screenshotPaths)==null?void 0:R[0];O&&C.push({entitySha:$.sha,entityName:$.name,scenarioId:I.id,scenarioName:I.name,screenshotPath:O,createdAt:D.createdAt||""})})}),C.sort(($,D)=>new Date(D.createdAt).getTime()-new Date($.createdAt).getTime());const E=C.slice(0,16),S=(i==null?void 0:i.filter($=>$.entityType==="visual").filter($=>{var _,I;const D=(_=$.analyses)==null?void 0:_[0];return!((I=D==null?void 0:D.scenarios)==null?void 0:I.some(O=>{var V,R;return(R=(V=O.metadata)==null?void 0:V.screenshotPaths)==null?void 0:R[0]}))}).slice(0,8))||[],A=(r=d==null?void 0:d.metadata)==null?void 0:r.currentRun,k=((a=A==null?void 0:A.currentEntityShas)==null?void 0:a.length)||0,T=s.jobs.length||0;return U({stats:{totalEntities:p,visualEntities:f,libraryEntities:g,uncommittedEntities:x,entitiesWithAnalyses:b,totalScenarios:v,capturedScreenshots:w,currentlyAnalyzing:k,filesOnQueue:T},uncommittedFiles:h,uncommittedEntitiesList:y,recentSimulations:E,visualEntitiesForSimulation:S,projectSlug:l,queueState:s,currentCommit:d})}catch(o){return console.error("Failed to load dashboard data:",o),U({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 Mp=Oe(function(){var L,G;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:o,visualEntitiesForSimulation:s,projectSlug:i,queueState:l,currentCommit:d}=We(),m=Ee(),u=nt(),{showToast:h}=Er();mt({source:"dashboard"});const[p,f]=M(new Set),[g,y]=M(null),[x,b]=M(!1),[v,w]=M(!1),{lastLine:C,isCompleted:E}=ht(i,!!g),{simulatingEntity:S,scenarios:A,scenarioStatuses:k,allScenariosCaptured:T}=oe(()=>{var Y,q;const j={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return j;const N=s==null?void 0:s.find(K=>K.sha===g);if(!N)return j;const z=(Y=N.analyses)==null?void 0:Y[0],W=(z==null?void 0:z.scenarios)||[],H=((q=z==null?void 0:z.status)==null?void 0:q.scenarios)||[],re=H.filter(K=>K.screenshotFinishedAt).length,J=W.length>0&&re===W.length;return{simulatingEntity:N,scenarios:W,scenarioStatuses:H,allScenariosCaptured:J}},[g,s]);ne(()=>{(E||T)&&y(null)},[E,T]);const $=(L=d==null?void 0:d.metadata)==null?void 0:L.currentRun,D=new Set(($==null?void 0:$.currentEntityShas)||[]),P=new Set(l.jobs.flatMap(j=>j.entityShas||[])),_=new Set(((G=l.currentlyExecuting)==null?void 0:G.entityShas)||[]),I=a.filter(j=>j.entityType==="visual"||j.entityType==="library"),O=I.filter(j=>!D.has(j.sha)&&!P.has(j.sha)&&!_.has(j.sha)),V=()=>{if(O.length===0){h("All entities are already queued or analyzing","info",3e3);return}const j=O.map(N=>N.sha);w(!0),h(`Starting analysis for ${O.length} entities...`,"info",3e3),m.submit({entityShas:j.join(",")},{method:"post",action:"/api/analyze"})};ne(()=>{if(m.state==="idle"&&m.data){const j=m.data;j.success?(console.log("[Analyze All] Success:",j.message),h(`Analysis started for ${j.entityCount} entities in ${j.fileCount} files. Watch the logs for progress.`,"success",6e3),w(!1)):j.error&&(console.error("[Analyze All] Error:",j.error),h(`Error: ${j.error}`,"error",8e3),w(!1))}},[m.state,m.data,h]);const R=j=>{f(N=>{const z=new Set(N);return z.has(j)?z.delete(j):z.add(j),z})},F=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-4",children:[n("img",{src:Ap,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,j=>j.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:F.map((j,N)=>n(ae,{to:j.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${j.color}`},children:c("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[c("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:j.label}),c("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[j.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:j.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${j.color}15`},children:[j.iconType==="folder"&&n(ti,{size:20,style:{color:j.color}}),j.iconType==="check"&&n(yr,{size:20,style:{color:j.color}}),j.iconType==="image"&&n(Wt,{size:20,style:{color:j.color}}),j.iconType==="code-xml"&&n(ni,{size:20,style:{color:j.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:j.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:j.color},children:"View All →"})]})]})},N))}),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"})]}),I.length>0&&n("button",{onClick:V,disabled:m.state!=="idle"||v||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:j=>j.currentTarget.style.backgroundColor="#004560",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||v?"Starting analysis...":O.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([j,N])=>{const z=p.has(j),W=N.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>R(j),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:z?"▼":"▶"}),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:j}),c("span",{className:"text-xs text-gray-500",children:[W.length," entit",W.length!==1?"ies":"y"]})]})]})}),z&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:W.length>0?W.map(H=>{const re=D.has(H.sha),J=P.has(H.sha)||_.has(H.sha);return c(ae,{to:`/entity/${H.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:Y=>Y.currentTarget.style.borderColor="#005C75",onMouseLeave:Y=>Y.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:H.entityType==="visual"?"#8B5CF615":H.entityType==="library"?"#6366F1":"#EC4899"},children:[H.entityType==="visual"&&n(Wt,{size:16,style:{color:"#8B5CF6"}}),H.entityType==="library"&&n(ao,{size:16,className:"text-white"}),H.entityType==="other"&&n(ri,{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:H.name}),H.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),H.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),H.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),H.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:H.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[re&&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(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}),!re&&J&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!re&&!J&&n("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),h(`Starting analysis for ${H.name}...`,"info",3e3),m.submit({entityShas:H.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:Y=>Y.currentTarget.style.backgroundColor="#004560",onMouseLeave:Y=>Y.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},H.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},j)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!g&&n(Ep,{recentSimulations:o}),g&&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:o.length>0?`Latest ${o.length} captured screenshot${o.length!==1?"s":""}`:"No simulations captured yet"})]})}),g&&c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[S&&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(Ue,{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 ",S.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:S.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":"",")"]})]}):C?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(Ze,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):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(Ze,{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(Ze,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map((j,N)=>{var q,K,B;const z=(q=S==null?void 0:S.analyses)==null?void 0:q[0],W=Fn(j,z==null?void 0:z.status,void 0,g||void 0,void 0),H=(B=(K=j.metadata)==null?void 0:K.screenshotPaths)==null?void 0:B[0],re=W.isCaptured,J=W.status==="capturing"||W.status==="starting",Y=W.hasError;return re?n(ae,{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(De,{screenshotPath:H,alt:j.name,title:j.name,className:"max-w-full max-h-full object-contain object-center"})},N):Y?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:W.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},N):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${J?"Capturing":"Pending"} ${j.name}...`,children:n("span",{className:J?"animate-pulse":"text-gray-400",children:J?"⋯":"⏹️"})},N)})})]})]})]}),x&&i&&n(dt,{projectSlug:i,onClose:()=>b(!1)})]})})}),_p=Object.freeze(Object.defineProperty({__proto__:null,default:Mp,loader:Pp,meta:kp},Symbol.toStringTag,{value:"Module"}));function or(e){return`${e.filePath||""}::${e.name}`}function cs(e,t){const r=Ee(),{showToast:a}=Er(),[o,s]=M(new Map);ne(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&a(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,a]),ne(()=>{var f;if(o.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(g=>{var y;(y=g.entityShas)==null||y.forEach(x=>{o.forEach((b,v)=>{b===x&&p.add(v)})})}),e==null||e.forEach(g=>{o.forEach((y,x)=>{y===g&&p.add(x)})}),p.size>0&&s(g=>{const y=new Map(g);return p.forEach(x=>y.delete(x)),y})},[t,e,o]);const i=se(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=or(p);s(y=>new Map(y).set(f,p.sha));const g=new FormData;g.append("entitySha",p.sha),g.append("filePath",p.filePath||""),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),l=se(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),s(x=>{const b=new Map(x);return f.forEach(v=>b.set(or(v),v.sha)),b});const g=f.map(x=>x.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),d=se(p=>(e==null?void 0:e.includes(p))??!1,[e]),m=se(p=>{const f=or(p);return o.has(f)},[o]),u=se(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(g=>{var y;return(y=g.entityShas)==null?void 0:y.includes(p)}))??!1},[t]),h=oe(()=>Array.from(o.keys()),[o]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:h}}function Br({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:o=!1,analyzeAllText:s="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"UNCOMMITTED"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),c("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:o,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:o?s:"Analyze all entities",children:s})})]})]})]})})}function Tp({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},a={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const s=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:s.textColor},children:s.label})})}const o=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${o.bgColor}`,title:e,children:o.label}),o.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 Ur({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:o,entityCount:s,state:i,lastModified:l,actionButton:d,uncommittedCount:m,children:u,isNotAnalyzable:h=!1,isUncommitted:p=!1}){return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[c("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(ho,{filePath:e}),a&&n(Tp,{status:typeof a=="string"?a:a.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&c("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:o}),c("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[s," ",s===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:os(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Wr({entities:e,maxPreviews:t=3}){var a,o,s,i,l;const r=[];for(const d of e){if(r.length>=t)break;const m=((o=(a=d.analyses)==null?void 0:a[0])==null?void 0:o.scenarios)||[];if(d.entityType==="library"){const u=m.find(h=>{var p,f;return((p=h.metadata)==null?void 0:p.executionResult)||((f=h.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=m.find(h=>{var p,f;return(f=(p=h.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const h=(i=(s=u.metadata)==null?void 0:s.screenshotPaths)==null?void 0:i[0],p=!!((l=u.metadata)!=null&&l.error);h&&r.push({type:"screenshot",screenshot:h,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ce,{children:r.map((d,m)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return c(ae,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(De,{screenshotPath:d.screenshot,alt:`Preview ${m+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(sr,{size:12,color:"white"})})]},`screenshot-${m}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(rs,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function Hr({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,h;const o=t||r?[{entityShas:[e.sha]}]:[],s=Ve(e,o,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(s==="not-analyzed"||s==="out-of-date")&&!t&&!r,m=(((h=(u=e.analyses)==null?void 0:u[0])==null?void 0:h.scenarios)||[]).filter(p=>{var f,g;return(g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return c("div",{className:"bg-white rounded-lg",children:[c(ae,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Ue,{type:"type"})})}):n(Ue,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(Fr,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?s==="queued"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):s==="analyzing"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):s==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):s==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),m.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:m.map((p,f)=>{var y,x;const g=(x=(y=p.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return g?n(ae,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(De,{screenshotPath:g,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function Ip({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:o,entityType:s,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:h,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[x,b]=Jt(),[v,w]=M(new Set),[C,E]=M(""),[S,A]=M(!1),[k,T]=M("all"),[$,D]=M("desc"),P=s||"all",_=oe(()=>{let N=e;return P!=="all"&&(N=N.filter(z=>z.entityType===P)),o==="analyzed"&&(N=N.filter(z=>z.analyses&&z.analyses.length>0)),N},[e,P,o]),I=oe(()=>{const N=new Map,z=new Map,W=new Map;_.forEach(Y=>{var B,Z;const q=`${Y.filePath}::${Y.name}`,K=z.get(q);if(!K)z.set(q,Y),W.set(q,[]);else{const de=((B=K.metadata)==null?void 0:B.editedAt)||K.createdAt||"",he=((Z=Y.metadata)==null?void 0:Z.editedAt)||Y.createdAt||"";let ye=!1;if(he>de)ye=!0;else if(he===de){const ve=K.createdAt||"";ye=(Y.createdAt||"")>ve}ye?(W.get(q).push(K),z.set(q,Y)):W.get(q).push(Y)}}),z.forEach((Y,q)=>{var B;if(!(Y.analyses&&Y.analyses.length>0)&&((B=Y.metadata)!=null&&B.previousVersionWithAnalyses)){const de=(W.get(q)||[]).find(he=>{var ye;return he.sha===((ye=Y.metadata)==null?void 0:ye.previousVersionWithAnalyses)});de&&de.analyses&&de.analyses.length>0&&(Y.analyses=de.analyses)}}),Array.from(z.values()).sort((Y,q)=>{var Z,de,he,ye;const K=!((Z=Y.metadata)!=null&&Z.notExported)&&!((de=Y.metadata)!=null&&de.namedExport),B=!((he=q.metadata)!=null&&he.notExported)&&!((ye=q.metadata)!=null&&ye.namedExport);return K&&!B?-1:!K&&B?1:0}).forEach(Y=>{var de,he,ye,ve,_e;const q=Y.filePath??"No File Path";N.has(q)||N.set(q,{filePath:q,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const K=N.get(q);K.entities.push(Y),K.totalCount++,(de=Y.metadata)!=null&&de.isUncommitted&&K.uncommittedCount++;const B=((ve=(ye=(he=Y.analyses)==null?void 0:he[0])==null?void 0:ye.scenarios)==null?void 0:ve.length)||0;K.simulationCount+=B;const Z=((_e=Y.metadata)==null?void 0:_e.editedAt)||Y.updatedAt;Z&&(!K.lastUpdated||new Date(Z)>new Date(K.lastUpdated))&&(K.lastUpdated=Z)});const H=(i==null?void 0:i.jobs)||[],re=Y=>{const q=`${Y.filePath||""}::${Y.name}`;return(d==null?void 0:d.includes(q))||!1};N.forEach(Y=>{const q=Y.entities.map(K=>re(K)?"queued":Ve(K,H));q.includes("analyzing")||q.includes("queued")?Y.state="analyzing":q.includes("incomplete")?Y.state="incomplete":q.includes("out-of-date")?Y.state="out-of-date":q.includes("not-analyzed")?Y.state="not-analyzed":Y.state="up-to-date"}),N.forEach(Y=>{var q,K,B,Z,de;for(const he of Y.entities){if(Y.previewScreenshots.length+Y.previewLibraryScenarios.length>=3)break;const ve=((K=(q=he.analyses)==null?void 0:q[0])==null?void 0:K.scenarios)||[];if(he.entityType==="library"){const _e=ve.find(Ne=>{var Ae,Te;return((Ae=Ne.metadata)==null?void 0:Ae.executionResult)||((Te=Ne.metadata)==null?void 0:Te.error)});_e&&Y.previewLibraryScenarios.push({scenario:_e,entitySha:he.sha})}else{const _e=ve.find(Ne=>{var Ae,Te;return(Te=(Ae=Ne.metadata)==null?void 0:Ae.screenshotPaths)==null?void 0:Te[0]});if(_e){const Ne=(Z=(B=_e.metadata)==null?void 0:B.screenshotPaths)==null?void 0:Z[0],Ae=!!((de=_e.metadata)!=null&&de.error);Ne&&!Y.previewScreenshots.includes(Ne)&&(Y.previewScreenshots.push(Ne),Y.previewScreenshotErrors.push(Ae))}}}});const J=Array.from(N.values());return J.sort((Y,q)=>{if(o==="analyzed"){const Z=Math.max(...Y.entities.filter(he=>{var ye,ve;return(ve=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:ve.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0),de=Math.max(...q.entities.filter(he=>{var ye,ve;return(ve=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:ve.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0);return $==="desc"?de-Z:Z-de}if(Y.uncommittedCount>0&&q.uncommittedCount===0)return-1;if(Y.uncommittedCount===0&&q.uncommittedCount>0)return 1;const K=Y.lastUpdated?new Date(Y.lastUpdated).getTime():0,B=q.lastUpdated?new Date(q.lastUpdated).getTime():0;return $==="desc"?B-K:K-B}),J},[_,o,$,i,d]),O=oe(()=>{let N=I;if(k!=="all"&&(N=N.filter(z=>z.state===k)),C.trim()){const z=C.toLowerCase();N=N.filter(W=>W.filePath.toLowerCase().includes(z))}return N},[I,C,k]),V=(t-1)*r,R=V+r,F=O.slice(V,R),L=Math.ceil(O.length/r),G=N=>{w(z=>{const W=new Set(z);return W.has(N)?W.delete(N):W.add(N),W})},j=()=>{D(N=>N==="desc"?"asc":"desc")};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:P,onChange:N=>{const z=N.target.value,W=new URLSearchParams(x);z==="all"?W.delete("entityType"):W.set("entityType",z),W.set("page","1"),b(W)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:k,onChange:N=>T(N.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(Ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(oo,{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:C,onChange:N=>E(N.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:O.length})," ",O.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:O.reduce((N,z)=>N+z.totalCount,0)})," ",O.reduce((N,z)=>N+z.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),g?c("button",{onClick:y,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[O.filter(N=>N.uncommittedCount>0).length," ","uncommitted"," ",O.filter(N=>N.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):c("button",{onClick:y,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),F.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:()=>{w(new Set(F.map(N=>N.filePath))),A(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:()=>{w(new Set),A(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),n(Br,{showActions:!0,sortOrder:$,onSortChange:j}),n("div",{className:"flex flex-col gap-[3px]",children:F.map(N=>{const z=v.has(N.filePath),H=N.entities.filter(q=>(q.entityType==="visual"||q.entityType==="library")&&(Ve(q,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(q,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(q,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,re=q=>{var K;return((K=a==null?void 0:a.currentEntityShas)==null?void 0:K.includes(q))||!1},J=q=>{var K;return l!=null&&l(q)?!0:((K=i==null?void 0:i.jobs)==null?void 0:K.some(B=>{var Z;return(Z=B.entityShas)==null?void 0:Z.includes(q.sha)}))||!1},Y=q=>{m==null||m(q)};return n(Ur,{filePath:N.filePath,isExpanded:z,onToggle:()=>G(N.filePath),simulationPreviews:n(Wr,{entities:N.entities,maxPreviews:1}),entityCount:N.totalCount,state:N.state,lastModified:N.lastUpdated,uncommittedCount:N.uncommittedCount,isUncommitted:N.uncommittedCount>0,actionButton:H?n("button",{onClick:q=>{q.stopPropagation();const K=N.entities.filter(B=>(B.entityType==="visual"||B.entityType==="library")&&(Ve(B,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(B,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(B,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(K)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:N.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:N.entities.sort((q,K)=>{const B=q.entityType==="visual"||q.entityType==="library",Z=K.entityType==="visual"||K.entityType==="library";return B&&!Z?-1:!B&&Z?1:0}).map(q=>n(Hr,{entity:q,isActivelyAnalyzing:re(q.sha),isQueued:J(q),onGenerateSimulation:Y},q.sha))},N.filePath)})}),L>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",L]}),t<L&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const $p=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function jp({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),o=r.searchParams.get("filter")||null,s=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([Zt(),Mt()]);return U({entities:d,currentCommit:m,page:a,filter:o,entityType:s,queueState:l})}catch(r){return console.error("Failed to load entities:",r),U({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Rp=Oe(function(){var C,E,S;const{entities:t,currentCommit:r,page:a,filter:o,entityType:s,queueState:i,error:l}=We();nt();const[d,m]=Jt(),[u,h]=M(!1);mt({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:g,pendingEntityKeys:y}=cs((E=(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun)==null?void 0:E.currentEntityShas,i),x=t||[],b=oe(()=>{const A=new Set([]);for(const k of x)A.add(k.filePath??"No File Path");return Array.from(A)},[x]),v=oe(()=>{let A=x;return u&&(A=A.filter(k=>{var T;return(T=k.metadata)==null?void 0:T.isUncommitted})),A.sort((k,T)=>{var $,D,P,_,I,O;return($=k.metadata)!=null&&$.isUncommitted&&!((D=T.metadata)!=null&&D.isUncommitted)?-1:!((P=k.metadata)!=null&&P.isUncommitted)&&((_=T.metadata)!=null&&_.isUncommitted)?1:new Date(((I=T.metadata)==null?void 0:I.editedAt)||0).getTime()-new Date(((O=k.metadata)==null?void 0:O.editedAt)||0).getTime()})},[x,u]),w=oe(()=>{var k;const A=new Set([]);for(const T of x)(k=T.metadata)!=null&&k.isUncommitted&&A.add(T.filePath??"No File Path");return Array.from(A)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:c("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),c("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Ip,{entities:v,page:a,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:o,entityType:s,queueState:i,isEntityPending:g,pendingEntityKeys:y,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:w.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})})}),Dp=Object.freeze(Object.defineProperty({__proto__:null,default:Rp,loader:jp,meta:$p},Symbol.toStringTag,{value:"Module"})),Lp=()=>[{title:"CodeYam - Rules"},{name:"description",content:"Manage Claude Rules documentation"}];async function Fp({request:e}){try{const[t,r]=await Promise.all([fetch(new URL("/api/rules",e.url).toString()),fetch(new URL("/api/rules?action=recent-changes",e.url).toString())]),a=await t.json(),o=await r.json();return a.error?U({rules:[],recentChanges:[],error:a.error}):U({rules:a.rules||[],recentChanges:o.changes||[],error:null})}catch(t){return console.error("Failed to load rules:",t),U({rules:[],recentChanges:[],error:"Failed to load rules"})}}const Op={architecture:"bg-blue-100 text-blue-800",testing:"bg-green-100 text-green-800",faq:"bg-amber-100 text-amber-800"},ds={architecture:"Architecture",testing:"Testing",faq:"FAQ"};function Yp({rule:e,onEdit:t,onDelete:r}){const[a,o]=M(!1),s=e.frontmatter.category||"faq",i=oe(()=>{var d;const l=e.body.match(/^#+ (.+)$/m);return l?l[1]:(d=e.filePath.split("/").pop())==null?void 0:d.replace(".md","")},[e.body,e.filePath]);return c("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"p-4 cursor-pointer hover:bg-gray-50",onClick:()=>o(!a),children:[c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex items-start gap-3",children:[n("button",{className:"mt-1 text-gray-400 cursor-pointer",children:a?n(Ct,{className:"w-4 h-4"}):n(xr,{className:"w-4 h-4"})}),c("div",{children:[n("h3",{className:"font-medium text-gray-900",children:i}),n("p",{className:"text-sm text-gray-500 mt-1 font-mono",children:e.filePath})]})]}),c("div",{className:"flex items-center gap-2",children:[n("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${Op[s]}`,children:ds[s]}),e.frontmatter.timestamp&&c("span",{className:"text-xs text-gray-400 flex items-center gap-1",children:[n(mi,{className:"w-3 h-3"}),new Date(e.frontmatter.timestamp).toLocaleDateString()]})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"mt-2 ml-7 flex flex-wrap gap-1",children:[e.frontmatter.paths.slice(0,3).map((l,d)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs font-mono",children:l},d)),e.frontmatter.paths.length>3&&c("span",{className:"px-2 py-0.5 text-gray-400 text-xs",children:["+",e.frontmatter.paths.length-3," more"]})]})]}),a&&n("div",{className:"border-t border-gray-100",children:c("div",{className:"p-4 bg-gray-50",children:[c("div",{className:"flex justify-end gap-2 mb-3",children:[c("button",{onClick:l=>{l.stopPropagation(),t(e)},className:"flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded cursor-pointer",children:[n(so,{className:"w-4 h-4"}),"Edit"]}),c("button",{onClick:l=>{l.stopPropagation(),r(e)},className:"flex items-center gap-1 px-3 py-1.5 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded cursor-pointer",children:[n(hi,{className:"w-4 h-4"}),"Delete"]})]}),n("div",{className:"bg-white p-4 rounded border border-gray-200 max-h-96 overflow-auto markdown-body",children:n(zi,{components:{h1:({children:l})=>n("h1",{className:"text-xl font-bold text-gray-900 mb-3 mt-4 first:mt-0",children:l}),h2:({children:l})=>n("h2",{className:"text-lg font-semibold text-gray-900 mb-2 mt-4 first:mt-0",children:l}),h3:({children:l})=>n("h3",{className:"text-base font-semibold text-gray-800 mb-2 mt-3",children:l}),p:({children:l})=>n("p",{className:"text-sm text-gray-700 mb-3",children:l}),ul:({children:l})=>n("ul",{className:"list-disc list-inside text-sm text-gray-700 mb-3 space-y-1",children:l}),ol:({children:l})=>n("ol",{className:"list-decimal list-inside text-sm text-gray-700 mb-3 space-y-1",children:l}),li:({children:l})=>n("li",{children:l}),code:({children:l,className:d})=>(d==null?void 0:d.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-sm font-mono overflow-x-auto mb-3",children:n("code",{children:l})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-sm font-mono text-gray-800",children:l}),pre:({children:l})=>n(ce,{children:l}),strong:({children:l})=>n("strong",{className:"font-semibold text-gray-900",children:l}),blockquote:({children:l})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:l})},children:e.body.trim()})})]})})]})}function Xa({rule:e,onSave:t,onCancel:r}){const[a,o]=M((e==null?void 0:e.filePath)||""),[s,i]=M((e==null?void 0:e.content)||m()),[l,d]=M(!!e);function m(){return`---
|
|
245
|
+
paths:
|
|
246
|
+
- '**/*.ts'
|
|
247
|
+
category: faq
|
|
248
|
+
timestamp: ${new Date().toISOString().split(".")[0]+"Z"}
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## Title
|
|
252
|
+
|
|
253
|
+
Description here.
|
|
254
|
+
|
|
255
|
+
**Learned:** ${new Date().toISOString().split("T")[0]} from [context]
|
|
256
|
+
`}const u=!e;return c("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:[c("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(oi,{className:"w-5 h-5"})})]}),u&&c("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:c("div",{className:"flex items-start gap-3",children:[n(si,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),c("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),n("code",{className:"block bg-white px-3 py-2 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam:new-rule"})]})]})}),c("button",{onClick:()=>d(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[l?n(Ct,{className:"w-4 h-4"}):n(xr,{className:"w-4 h-4"}),"Or create manually"]})]}),(l||!u)&&c("div",{className:"space-y-4",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),n("input",{type:"text",value:a,onChange:h=>o(h.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:s,onChange:h=>i(h.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm"})]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"flex items-center gap-1 px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),c("button",{onClick:()=>t(a,s),disabled:!a.trim()||!s.trim(),className:"flex items-center gap-1 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",children:[n(ii,{className:"w-4 h-4"}),"Save"]})]})]})]})}function zp({changes:e,rules:t,onEditRule:r}){const[a,o]=M(!1),[s,i]=M(()=>new Set(e.filter(g=>g.commitHash==="uncommitted").map(g=>g.commitHash))),l=oe(()=>e.some(g=>g.commitHash==="uncommitted"),[e]),d=oe(()=>{const g=new Date;return g.setDate(g.getDate()-5),g},[]),m=oe(()=>e.some(g=>new Date(g.date)>=d),[e,d]),u=oe(()=>{if(a)return e;const g=e.filter(x=>x.commitHash==="uncommitted"),y=e.filter(x=>x.commitHash!=="uncommitted");return!m&&g.length===0?[]:[...g,...y.slice(0,3)]},[e,a,m]),h=g=>{i(y=>{const x=new Set(y);return x.has(g)?x.delete(g):x.add(g),x})},p=g=>t.find(y=>y.filePath===g),f=g=>{const y=new Date(g),b=new Date().getTime()-y.getTime(),v=Math.floor(b/(1e3*60*60*24));return v===0?"Today":v===1?"Yesterday":v<7?`${v} days ago`:y.toLocaleDateString()};return e.length===0?null:!m&&!l&&!a?n("div",{className:"mb-8",children:c("button",{onClick:()=>o(!0),className:"flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 cursor-pointer",children:[n(ba,{className:"w-4 h-4"}),"View ",e.length," older change",e.length!==1?"s":""]})}):c("div",{className:"mb-8",children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h2",{className:"text-lg font-semibold text-gray-900 flex items-center gap-2",children:[n(li,{className:"w-5 h-5 text-gray-500"}),"Recent Changes"]}),e.length>3&&n("button",{onClick:()=>o(!a),className:"text-sm text-[#005C75] hover:underline flex items-center gap-1 cursor-pointer",children:a?c(ce,{children:[n(ci,{className:"w-4 h-4"}),"Show Less"]}):c(ce,{children:[n(ba,{className:"w-4 h-4"}),"View All (",e.length,")"]})})]}),n("div",{className:"space-y-3",children:u.map(g=>{const y=g.commitHash==="uncommitted";return c("div",{className:`rounded-lg border overflow-hidden ${y?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,children:[n("div",{className:`p-4 cursor-pointer ${y?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>h(g.commitHash),children:n("div",{className:"flex items-start justify-between",children:c("div",{className:"flex items-start gap-3",children:[n("button",{className:`mt-0.5 cursor-pointer ${y?"text-amber-600":"text-gray-400"}`,children:s.has(g.commitHash)?n(Ct,{className:"w-4 h-4"}):n(xr,{className:"w-4 h-4"})}),c("div",{children:[c("p",{className:`font-medium ${y?"text-amber-900":"text-gray-900"}`,children:[g.message,y&&n("span",{className:"ml-2 text-xs bg-amber-200 text-amber-800 px-2 py-0.5 rounded-full",children:"Not committed"})]}),c("div",{className:`flex items-center gap-3 mt-1 text-sm ${y?"text-amber-700":"text-gray-500"}`,children:[!y&&n("span",{className:"font-mono text-xs bg-gray-100 px-1.5 py-0.5 rounded",children:g.commitHash}),n("span",{children:f(g.date)}),c("span",{children:[g.files.length," file",g.files.length!==1?"s":""]})]})]})]})})}),s.has(g.commitHash)&&n("div",{className:"border-t border-gray-100",children:g.files.map((x,b)=>{const v=p(x.filePath);return c("div",{className:"border-b border-gray-100 last:border-b-0",children:[c("div",{className:"px-4 py-2 bg-gray-50 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[x.changeType==="added"&&n(ir,{className:"w-4 h-4 text-green-600"}),x.changeType==="modified"&&n(di,{className:"w-4 h-4 text-amber-600"}),x.changeType==="deleted"&&n(ui,{className:"w-4 h-4 text-red-600"}),n("span",{className:"font-mono text-sm",children:x.filePath}),n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.changeType==="added"?"bg-green-100 text-green-700":x.changeType==="deleted"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:x.changeType})]}),v&&x.changeType!=="deleted"&&c("button",{onClick:w=>{w.stopPropagation(),r(v)},className:"flex items-center gap-1 px-2 py-1 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded cursor-pointer",children:[n(so,{className:"w-3 h-3"}),"Edit"]})]}),x.diff&&n("pre",{className:"p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto",children:x.diff.split(`
|
|
257
|
+
`).map((w,C)=>{let E="";return w.startsWith("+")&&!w.startsWith("+++")?E="text-green-400":w.startsWith("-")&&!w.startsWith("---")?E="text-red-400":w.startsWith("@@")&&(E="text-cyan-400"),n("div",{className:E,children:w},C)})})]},b)})})]},g.commitHash)})})]})}const Bp=Oe(function(){const{rules:t,recentChanges:r,error:a}=We(),o=Ee(),s=nt(),[i,l]=M(null),[d,m]=M(null),[u,h]=M(!1),[p,f]=M(null);mt({source:"rules-page"}),ne(()=>{o.state==="idle"&&o.data&&(s.revalidate(),m(null),h(!1))},[o.state,o.data,s]);const g=oe(()=>i?t.filter(w=>w.frontmatter.category===i):t,[t,i]),y=oe(()=>{const w={};for(const C of g){const E=C.filePath.includes("/")?C.filePath.split("/").slice(0,-1).join("/"):"(root)";w[E]||(w[E]=[]),w[E].push(C)}return Object.entries(w).sort(([C],[E])=>C.localeCompare(E))},[g]),x=(w,C)=>{const E=d?"update":"create";o.submit({action:E,filePath:w,content:C},{method:"POST",action:"/api/rules",encType:"application/json"})},b=w=>{o.submit({action:"delete",filePath:w.filePath},{method:"POST",action:"/api/rules",encType:"application/json"}),f(null)},v=oe(()=>{const w={architecture:0,testing:0,faq:0};for(const C of t){const E=C.frontmatter.category||"faq";w[E]++}return w},[t]);return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[c("div",{className:"flex items-center justify-between",children:[c("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Claude Rules"}),n("p",{className:"text-[15px] text-gray-500",children:"Documentation that helps Claude understand your codebase patterns and conventions."})]}),c("button",{onClick:()=>h(!0),className:"flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(ir,{className:"w-4 h-4"}),"New Rule"]})]}),u&&n("div",{className:"mt-4",children:n(Xa,{rule:null,onSave:x,onCancel:()=>{h(!1)}})})]}),d&&n("div",{className:"mb-8",children:n(Xa,{rule:d,onSave:x,onCancel:()=>{m(null)}})}),n(zp,{changes:r,rules:t,onEditRule:m}),c("div",{className:"grid grid-cols-4 gap-4 mb-8",children:[c("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[n("div",{className:"text-2xl font-semibold text-gray-900",children:t.length}),n("div",{className:"text-sm text-gray-500",children:"Total Rules"})]}),c("div",{className:`bg-white rounded-lg border border-gray-200 p-4 cursor-pointer hover:border-blue-300 ${i==="architecture"?"ring-2 ring-blue-500":""}`,onClick:()=>l(i==="architecture"?null:"architecture"),children:[n("div",{className:"text-2xl font-semibold text-blue-600",children:v.architecture}),n("div",{className:"text-sm text-gray-500",children:"Architecture"})]}),c("div",{className:`bg-white rounded-lg border border-gray-200 p-4 cursor-pointer hover:border-green-300 ${i==="testing"?"ring-2 ring-green-500":""}`,onClick:()=>l(i==="testing"?null:"testing"),children:[n("div",{className:"text-2xl font-semibold text-green-600",children:v.testing}),n("div",{className:"text-sm text-gray-500",children:"Testing"})]}),c("div",{className:`bg-white rounded-lg border border-gray-200 p-4 cursor-pointer hover:border-amber-300 ${i==="faq"?"ring-2 ring-amber-500":""}`,onClick:()=>l(i==="faq"?null:"faq"),children:[n("div",{className:"text-2xl font-semibold text-amber-600",children:v.faq}),n("div",{className:"text-sm text-gray-500",children:"FAQ / Gotchas"})]})]}),p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:c("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Rule?"}),c("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:p.filePath}),"? This cannot be undone."]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:()=>f(null),className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>b(p),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})}),t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(xa,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),c("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam:power-rules"})," ","to generate initial rules for your codebase."]}),c("button",{onClick:()=>h(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(ir,{className:"w-4 h-4"}),"Create Your First Rule"]})]}):c("div",{className:"space-y-6",children:[i&&c("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n(ai,{className:"w-4 h-4"}),"Showing"," ",ds[i]," ","rules",n("button",{onClick:()=>l(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),y.map(([w,C])=>c("div",{children:[c("h2",{className:"text-sm font-medium text-gray-500 mb-3 flex items-center gap-2",children:[n(xa,{className:"w-4 h-4"}),w]}),n("div",{className:"space-y-3",children:C.map(E=>n(Yp,{rule:E,onEdit:m,onDelete:f},E.filePath))})]},w))]})]})})}),Up=Object.freeze(Object.defineProperty({__proto__:null,default:Bp,loader:Fp,meta:Lp},Symbol.toStringTag,{value:"Module"}));function Wp(e,t,r){const[a,o]=M(()=>new Set),[s,i]=M(()=>new Set),l=Se([]),d=Se([]);return ne(()=>{(t.length!==l.current.length||t.some((y,x)=>y!==l.current[x]))&&(l.current=t,o(y=>{const x=new Set;return t.forEach(b=>{y.has(b)&&x.add(b)}),x}))},[t]),ne(()=>{(r.length!==d.current.length||r.some((y,x)=>y!==d.current[x]))&&(d.current=r,i(y=>{const x=new Set;return r.forEach(b=>{y.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:a,expandedBranch:s,setExpandedUncommitted:o,setExpandedBranch:i,toggleFile:(g,y,x)=>{x(b=>{const v=new Set(b);return v.has(g)?v.delete(g):v.add(g),v})},expandAllUncommitted:()=>{o(new Set(t))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Hp(e,t,r){const[a,o]=M(null),[s,i]=M(null),l=Ee();ne(()=>{var h,p;((h=l.data)==null?void 0:h.oldContent)!==void 0&&((p=l.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=h=>{o({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},m=(h,p)=>{o({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},u=()=>{o(null),i(null)};return{diffView:a,diffContent:s,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function qp({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:o}){var m;const[s,i]=M(!1),[l,d]=M(!1);return ne(()=>{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:"," ",((m=a.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!s),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:s?"Show changes only":"Show full file",children:s?"Show Changes Only":"Show Full File"}),n("button",{onClick:o,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Bi,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!s,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):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:o,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function Gp({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:o,expandedFiles:s,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:m,onBranchChange:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=e.flatMap(([w,{entities:C}])=>{const E=C.filter(S=>i(S.sha)||l(S)).map(S=>S.sha);return E.length>0?[{entityShas:E}]:[]}),b=w=>{const C=w.map(E=>Ve(E,x));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},v=oe(()=>[...e].sort((w,C)=>{const E=w[1].entities.reduce((T,$)=>{var P;const D=((P=$.metadata)==null?void 0:P.editedAt)||$.updatedAt;return D?T?new Date(D)>new Date(T)?D:T:D:T},null),S=C[1].entities.reduce((T,$)=>{var P;const D=((P=$.metadata)==null?void 0:P.editedAt)||$.updatedAt;return D?T?new Date(D)>new Date(T)?D:T:D:T},null);if(!E&&!S)return 0;if(!E)return 1;if(!S)return-1;const A=new Date(E).getTime(),k=new Date(S).getTime();return d==="desc"?k-A:A-k}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(Br,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([w,{status:C,entities:E,isUncommitted:S}])=>{const A=s.has(w),k=b(E),T=E.reduce((_,I)=>{var V;const O=((V=I.metadata)==null?void 0:V.editedAt)||I.updatedAt;return O?_?new Date(O)>new Date(_)?O:_:O:_},null),D=E.filter(_=>_.entityType==="visual"||_.entityType==="library").length===0;let P;return D?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?P=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?P=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):k==="out-of-date"?P=n("button",{onClick:_=>{_.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>h(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):k==="not-analyzed"&&(P=n("button",{onClick:_=>{_.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>h(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ur,{filePath:w,isExpanded:A,onToggle:()=>m(w),fileStatus:C,isUncommitted:S,simulationPreviews:n(Wr,{entities:E,maxPreviews:1}),entityCount:E.length,state:k,lastModified:T,isNotAnalyzable:D,actionButton:P,children:E.sort((_,I)=>{const O=_.entityType==="visual"||_.entityType==="library",V=I.entityType==="visual"||I.entityType==="library";return O&&!V?-1:!O&&V?1:0}).map(_=>n(Hr,{entity:_,isActivelyAnalyzing:i(_.sha),isQueued:l(_),onGenerateSimulation:h},_.sha))},w)})})]}):c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Jp({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:o,projectSlug:s,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=oe(()=>{const w=[];return e.forEach(([C,{editedEntities:E}])=>{const S=E.filter(A=>a(A.sha)||o(A)).map(A=>A.sha);S.length>0&&w.push({entityShas:S})}),w},[e,a,o]),b=oe(()=>{const w=new Map;return e.forEach(([C,{editedEntities:E}])=>{const S=E.map($=>Ve($,x));let A;S.includes("analyzing")||S.includes("queued")?A="analyzing":S.includes("out-of-date")?A="out-of-date":S.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const k=E.reduce(($,D)=>{var _;const P=((_=D.metadata)==null?void 0:_.editedAt)||D.updatedAt;return P&&(!$||new Date(P)>new Date($))?P:$},null),T=E.filter($=>$.entityType==="visual"||$.entityType==="library").length;w.set(C,{state:A,lastModified:k,analyzableCount:T})}),w},[e,x]),v=oe(()=>[...e].sort((w,C)=>{const E=b.get(w[0]),S=b.get(C[0]),A=E==null?void 0:E.lastModified,k=S==null?void 0:S.lastModified;if(!A&&!k)return 0;if(!A)return 1;if(!k)return-1;const T=new Date(A).getTime(),$=new Date(k).getTime();return d==="desc"?$-T:T-$}),[e,b,d]);return e.length===0?c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):c("div",{children:[n(Br,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([w,{status:C,editedEntities:E}])=>{const S=r.has(w),A=b.get(w),{state:k,lastModified:T,analyzableCount:$}=A,D=$===0;let P;return D?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?P=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?P=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):k==="out-of-date"?P=n("button",{onClick:_=>{_.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!a(I.sha)&&!o(I)).forEach(I=>h(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):k==="not-analyzed"&&(P=n("button",{onClick:_=>{_.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!a(I.sha)&&!o(I)).forEach(I=>h(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ur,{filePath:w,isExpanded:S,onToggle:()=>m(w),fileStatus:C,simulationPreviews:n(Wr,{entities:E,maxPreviews:1}),entityCount:E.length,state:k,lastModified:T,isNotAnalyzable:D,isUncommitted:!0,actionButton:P,children:E.sort((_,I)=>{const O=_.entityType==="visual"||_.entityType==="library",V=I.entityType==="visual"||I.entityType==="library";return O&&!V?-1:!O&&V?1:0}).map(_=>n(Hr,{entity:_,isActivelyAnalyzing:a(_.sha),isQueued:o(_),onGenerateSimulation:h},_.sha))},w)})})]})}function Vp({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),c("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const Qp=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Kp({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),o=t.get("diffType"),s=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return o==="branch"?d=mn(a,s,i):d=em(a),U({...d,entitySha:l})}return U({error:"Unknown action"},{status:400})}async function Zp({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),o=r.searchParams.get("viewBranch"),s=t.analysisQueue,i=s?s.getState():{paused:!1,jobs:[]},[l,d,m]=await Promise.all([Zt(),Mt(),Ye()]),u=Zo(),h=Vu(),p=Qu(),f=Ku(),g=o||h,y=a||p;let x=[];return g&&g!==y&&(x=Xo(y,g)),U({entities:l||[],gitStatus:u,currentBranch:g,actualCurrentBranch:h,defaultBranch:p,allBranches:f,baseBranch:y,branchDiff:x,currentCommit:d,projectSlug:m,queueState:i})}catch(r){return console.error("Failed to load git data:",r),U({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const Xp=Oe(function(){var we,tn;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:o,defaultBranch:s,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:m,projectSlug:u,queueState:h}=We();mt({source:"git-page"});const[p,f]=Jt(),[g,y]=M(null),[x,b]=M("desc"),[v,w]=M("branch"),C=p.get("expanded")==="true",E=()=>{b(le=>le==="desc"?"asc":"desc")},S=Ee(),A=S.data;ne(()=>{a&&l&&a!==l&&S.state==="idle"&&!A&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(a)}`)},[a,l,S,A]);const k=oe(()=>{const le=is(r,t);return Array.from(le.entries()).sort((qe,Ge)=>qe[0].localeCompare(Ge[0]))},[r,t]),T=oe(()=>{const le=Np(d,t,A);return Array.from(le.entries()).sort((qe,Ge)=>qe[0].localeCompare(Ge[0]))},[d,t,A]),$=oe(()=>Sp(r,t),[r,t]),D=oe(()=>v==="uncommitted"?k:T,[v,k,T]),P=oe(()=>D.map(([le])=>le),[D]),{expandedUncommitted:_,setExpandedUncommitted:I,toggleFile:O,expandAllUncommitted:V,collapseAllUncommitted:R}=Wp(C,P,[]),{diffView:F,diffContent:L,isLoading:G,handleShowFileDiff:j,handleCloseDiff:N}=Hp(l,a),z=(we=m==null?void 0:m.metadata)==null?void 0:we.currentRun,W=new Set((z==null?void 0:z.currentEntityShas)||[]),H=new Set(h.jobs.flatMap(le=>le.entityShas||[])),re=new Set(((tn=h.currentlyExecuting)==null?void 0:tn.entityShas)||[]),{isAnalyzing:J,handleGenerateSimulation:Y,handleGenerateAllSimulations:q,isEntityBeingAnalyzed:K,isEntityPending:B}=cs(z==null?void 0:z.currentEntityShas,h),Z=le=>B(le)||H.has(le.sha)||re.has(le.sha),de=le=>{le===(o||a)?p.delete("viewBranch"):p.set("viewBranch",le),f(p)},he=le=>{le===s?p.delete("compare"):p.set("compare",le),f(p)},ye=()=>{const qe=D.flatMap(([Ge,On])=>On.editedEntities||On.entities||[]).filter(Ge=>!W.has(Ge.sha)&&!H.has(Ge.sha)&&!re.has(Ge.sha)&&!B(Ge));q(qe)},ve=k.length,_e=T.length,Ne=D.flatMap(([le,qe])=>qe.editedEntities||qe.entities||[]),Ae=Ne.filter(le=>le.entityType==="visual"||le.entityType==="library"),Te=Ae.length>0&&Ae.every(le=>W.has(le.sha)),ge=Ae.length>0&&!Te&&Ae.every(le=>H.has(le.sha)||re.has(le.sha)),je=J||Te||ge,ke=Te?"Analyzing...":ge?"Queued...":J?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),c("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Vp,{activeTab:v,onTabChange:w,uncommittedCount:ve,branchCount:_e})}),a&&v==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===s?c("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:s}),"."]}):c("div",{className:"flex gap-6 items-center",children:[c("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?c("div",{className:"relative w-50",children:[n("select",{value:a,onChange:le=>de(le.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(le=>n("option",{value:le,children:le},le))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),c("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:le=>he(le.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(le=>le!==a).map(le=>n("option",{value:le,children:le},le))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:c("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:D.length})," ","modified ",D.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Ne.length})," ",Ne.length===1?"entity":"entities"]})]}),D.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:V,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:R,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),c("div",{className:"overflow-hidden",children:[v==="branch"&&a&&n(Gp,{files:T,currentBranch:a,defaultBranch:s,baseBranch:l,allBranches:i,expandedFiles:_,isEntityBeingAnalyzed:K,isEntityQueued:Z,sortOrder:x,onToggleFile:le=>O(le,_,I),onBranchChange:he,onGenerateSimulation:Y,onSortChange:E,onAnalyzeAll:ye,analyzeAllDisabled:je,analyzeAllText:ke}),v==="uncommitted"&&n(Jp,{files:k,entityImpactMap:$,expandedFiles:_,isEntityBeingAnalyzed:K,isEntityQueued:Z,projectSlug:u,baseBranch:l,currentBranch:a,sortOrder:x,onToggleFile:le=>O(le,_,I),onShowFileDiff:j,onGenerateSimulation:Y,onSortChange:E,onAnalyzeAll:ye,analyzeAllDisabled:je,analyzeAllText:ke})]}),F&&n(qp,{diffView:F,diffContent:L,isLoading:G,entities:t,onClose:N}),g&&u&&n(dt,{projectSlug:u,onClose:()=>y(null)})]})})}),ef=Object.freeze(Object.defineProperty({__proto__:null,action:Kp,default:Xp,loader:Zp,meta:Qp},Symbol.toStringTag,{value:"Module"})),Gf={entry:{module:"/assets/entry.client-CS2cb_eZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-Bz5TunQg.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-D4TZhLuw.js","/assets/useReportContext-DYxHZQuP.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/git-commit-horizontal-CysbcZxi.js","/assets/useToast-mBRpZPiu.js","/assets/useLastLogLine-aSv48UbS.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/chevron-down-Cx24_aWc.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DavjRmOY.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/cy-logo-cli-DcX-ZS3p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-CTBG2mmz.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-D1T4TGjf.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DoLIqZX2.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/LogViewer-xgeCVgSM.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js"],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._-C2N4Op8e.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/InteractivePreview-aht4aafF.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/LoadingDots-B0GLXMsr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-DEx02QDa.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/LogViewer-xgeCVgSM.js","/assets/useReportContext-DYxHZQuP.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/ReportIssueModal-D4TZhLuw.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-DwFIBT09.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!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/api.rules":{id:"routes/api.rules",parentId:"root",path:"api/rules",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.rules-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-BRb-0kQl.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/ScenarioViewer-DEx02QDa.js","/assets/InteractivePreview-aht4aafF.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/LogViewer-xgeCVgSM.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-D4TZhLuw.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/scenarioStatus-B_8jpV3e.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-CS5f3WzT.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-BwqWJOgH.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useToast-mBRpZPiu.js","/assets/useReportContext-DYxHZQuP.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/loader-circle-B7B9V-bu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/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-Cs4MdYtv.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-BXhEawa3.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/rules":{id:"routes/rules",parentId:"root",path:"rules",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/rules-hEkvVw2-.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/chevron-down-Cx24_aWc.js","/assets/git-commit-horizontal-CysbcZxi.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-B4RJRvYB.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-BXhEawa3.js","/assets/LogViewer-xgeCVgSM.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-f874c610.js",version:"f874c610",sri:void 0},Jf="build/client",Vf="/",Qf={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Kf=!0,Zf=!1,Xf=[],eg={mode:"lazy",manifestPath:"/__manifest"},tg="/",ng={module:Wi},rg={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:id},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:md},"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:jd},"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:zd},"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:Yu},"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:Uu},"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:lm},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:dm},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:pm},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:ym},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:vm},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Nm},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Em},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Lm},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:zm},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:Hm},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Gm},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Vm},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Km},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:sh},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:ch},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:uh},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Rh},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Fh},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Hh},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Gh},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:Vh},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:ep},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:rp},"routes/api.rules":{id:"routes/api.rules",parentId:"root",path:"api/rules",index:void 0,caseSensitive:void 0,module:cp},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:mp},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:bp},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:wp},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:_p},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Dp},"routes/rules":{id:"routes/rules",parentId:"root",path:"rules",index:void 0,caseSensitive:void 0,module:Up},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:ef}};export{Zl as A,Ql as B,be as C,Cl as D,Nl as E,Pt as F,dl as G,fo as H,hl as I,go as J,gl as K,xl as L,Jf as M,Vf as N,Qf as O,ll as P,Kf as Q,Zf as R,Mr as S,Xf as T,eg as U,tg as V,ng as W,rg as X,Gf as Y,rl as a,Tt as b,kt as c,rt as d,Qt as e,Ar as f,kr as g,po as h,tl as i,$l as j,jl as k,ut as l,at as m,bo as n,Bl as o,gn as p,Et as q,vo as r,wo as s,Gl as t,ct as u,Co as v,$t as w,Jl as x,Ea as y,ec as z};
|