@codeyam/codeyam-cli 0.1.0-staging.596f0eb → 0.1.0-staging.62d4615
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 +16 -12
- package/analyzer-template/packages/ai/index.ts +20 -5
- package/analyzer-template/packages/ai/package.json +3 -3
- package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +214 -24
- package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +205 -10
- package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
- 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 +1518 -125
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +318 -5
- 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 +2301 -348
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +7 -2
- 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/BatchSchemaProcessor.ts +16 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +93 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +422 -86
- 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 +63 -2
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1394 -92
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +578 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2267 -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 +328 -7
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
- 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 +824 -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 +127 -3
- package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
- package/analyzer-template/packages/analyze/index.ts +2 -0
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
- 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/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +522 -272
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +34 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
- 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/analyzeRemixRoute.ts +4 -5
- package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -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 +625 -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 +550 -137
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -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 +917 -130
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
- package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
- package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
- 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/package.json +1 -1
- package/analyzer-template/packages/database/src/lib/kysely/db.ts +12 -5
- package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
- package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
- package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
- package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
- package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
- package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
- package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
- package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
- package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
- package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +7 -3
- package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
- 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.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +10 -3
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
- 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/commitsTable.d.ts +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.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/loadAnalyses.d.ts +2 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.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/database/src/lib/updateCommitMetadata.d.ts +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.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/Commit.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/Commit.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/ProjectMetadata.d.ts +3 -0
- package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.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 +199 -3
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/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/package.json +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/Commit.ts +2 -0
- package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
- package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +1 -0
- package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
- package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
- package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
- 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/Commit.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/Commit.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/ProjectMetadata.d.ts +3 -0
- package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.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 +199 -3
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/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 +57 -26
- package/analyzer-template/playwright/captureStatic.ts +1 -1
- 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 +9 -0
- package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
- package/analyzer-template/project/analyzeFileEntities.ts +4 -0
- package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
- package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
- package/analyzer-template/project/constructMockCode.ts +1268 -167
- package/analyzer-template/project/controller/startController.ts +16 -1
- package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
- package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
- package/analyzer-template/project/loadReadyToBeCaptured.ts +65 -41
- package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
- package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
- package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
- package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
- package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
- package/analyzer-template/project/orchestrateCapture.ts +81 -9
- 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 +61 -15
- package/analyzer-template/project/startScenarioCapture.ts +79 -41
- package/analyzer-template/project/writeMockDataTsx.ts +405 -65
- package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
- package/analyzer-template/project/writeScenarioComponents.ts +862 -183
- package/analyzer-template/project/writeScenarioFiles.ts +26 -0
- package/analyzer-template/project/writeSimpleRoot.ts +31 -23
- package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
- 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 +7 -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 +7 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
- package/background/src/lib/virtualized/project/constructMockCode.js +1126 -126
- 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/createEntitiesAndSortFiles.js +73 -1
- package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.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/loadReadyToBeCaptured.js +19 -8
- package/background/src/lib/virtualized/project/loadReadyToBeCaptured.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/AwsCaptureTaskRunner.js +2 -2
- package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.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 +73 -36
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture.js +65 -10
- 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 +53 -15
- 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 +354 -54
- 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 +624 -127
- 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 +31 -21
- package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +180 -0
- package/codeyam-cli/scripts/apply-setup.js.map +1 -1
- package/codeyam-cli/src/cli.js +9 -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 +42 -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/memory.js +264 -0
- package/codeyam-cli/src/commands/memory.js.map +1 -0
- 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 +29 -15
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/backgroundServer.js +18 -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 +76 -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 +249 -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/ruleReflection/__tests__/confusionDetector.test.js +82 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +128 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +75 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +285 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +83 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
- package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +96 -0
- package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
- package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +33 -0
- package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
- package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
- package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
- package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
- package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
- package/codeyam-cli/src/utils/rules/index.js +6 -0
- package/codeyam-cli/src/utils/rules/index.js.map +1 -0
- package/codeyam-cli/src/utils/rules/parser.js +78 -0
- package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js +18 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
- package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
- package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
- package/codeyam-cli/src/utils/rules/staleness.js +137 -0
- package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
- 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 +104 -3
- 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/CopyButton-CA3JxPb7.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-B86KKU7e.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-efWKDYMr.js → EntityTypeBadge-B5ctlSYt.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BqY8gDAW.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-ClaLpuOo.js +34 -0
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-BDhPilK7.js +25 -0
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-VeqEBv9v.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-Bs7Nn1Jr.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-Bm3PmcCz.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-C6PKeMYR.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Gq3Ocjo6.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BNLaXBHR.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-COPstp9J.js → TruncatedFilePath-CiwXDxLh.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/_index-B3TDXxnk.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DD1r_QU0.js +27 -0
- package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DfKzxuoe.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-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.save-fixture-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/book-open-PttOB2SF.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-TJp6ofnp.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-JE9ZIoBl.js +51 -0
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-CXhHQYrI.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/copy-6y9ALfGT.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-Ca9fAY46.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-C5lqplTC.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-n38keI1k.js +23 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CBoafmVs.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DGgZjdFg.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-38yPijoD.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-BSHEfydn.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-DCPhhSMo.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-Dk8wkAS7.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-DXnyr8uP.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-Bh6jH0cL.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-CcsFv748.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-ChN9-fAY.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/labs-BUvfJMNR.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-CTqLEAGU.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-d4e77269.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/memory-DCHBwHou.js +76 -0
- package/codeyam-cli/src/webserver/build/client/assets/pause-D6vreykR.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/root-D6oziHts.js +62 -0
- package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/search-B8VUL8nl.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-B2X7lJgQ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-CPoAg7Zo.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/terminal-BrCP7uQo.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BZz2NjYa.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-DNwUduNu.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-3pmpUQB-.js → useLastLogLine-COky1GVF.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CpZgwliL.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useToast-DEyawJ8r.js → useToast-Bv9JFvUO.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-C0KrUQp-.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-C2h1v1XD.js +260 -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-memory-hook.sh +199 -0
- package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam:debug.md} +48 -4
- package/codeyam-cli/templates/codeyam:diagnose.md +803 -0
- package/codeyam-cli/templates/codeyam:memory.md +404 -0
- package/codeyam-cli/templates/codeyam:new-rule.md +13 -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/codeyam-cli/templates/rule-notification-hook.py +54 -0
- package/codeyam-cli/templates/rule-reflection-hook.py +428 -0
- package/codeyam-cli/templates/rules-instructions.md +123 -0
- package/package.json +22 -19
- package/packages/ai/index.js +8 -6
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +167 -13
- 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 +154 -9
- 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 +138 -23
- package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
- package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.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 +1157 -103
- 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 +1816 -216
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +7 -2
- 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/BatchSchemaProcessor.js +13 -3
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
- package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +83 -1
- 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/convertTypeAnnotationsToValues.js +173 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +355 -77
- 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 +50 -1
- package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +1109 -85
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +400 -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 +1646 -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 +270 -7
- package/packages/ai/src/lib/isolateScopes.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +88 -46
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
- 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 +677 -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 +98 -1
- package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
- package/packages/analyze/index.js +1 -0
- package/packages/analyze/index.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
- package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/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/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +268 -52
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +24 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
- package/packages/analyze/src/lib/files/analyze/dependencyResolver.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/gatherEntityMap.js +2 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
- 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/analyzeRemixRoute.js +3 -2
- package/packages/analyze/src/lib/files/analyzeRemixRoute.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/getImportedExports.js +11 -7
- package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
- package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -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 +483 -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 +404 -85
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -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 +768 -117
- 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/analyze/src/lib/files/setImportedExports.js +2 -1
- package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/index.js +1 -0
- package/packages/analyze/src/lib/index.js.map +1 -1
- package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
- package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
- package/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 +10 -3
- package/packages/database/src/lib/kysely/db.js.map +1 -1
- package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
- package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
- 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/loadAnalyses.js +45 -2
- package/packages/database/src/lib/loadAnalyses.js.map +1 -1
- package/packages/database/src/lib/loadAnalysis.js +8 -0
- package/packages/database/src/lib/loadAnalysis.js.map +1 -1
- package/packages/database/src/lib/loadBranch.js +11 -1
- package/packages/database/src/lib/loadBranch.js.map +1 -1
- package/packages/database/src/lib/loadCommit.js +7 -0
- package/packages/database/src/lib/loadCommit.js.map +1 -1
- package/packages/database/src/lib/loadCommits.js +22 -1
- package/packages/database/src/lib/loadCommits.js.map +1 -1
- package/packages/database/src/lib/loadEntities.js +23 -4
- package/packages/database/src/lib/loadEntities.js.map +1 -1
- package/packages/database/src/lib/loadEntityBranches.js +9 -0
- package/packages/database/src/lib/loadEntityBranches.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/database/src/lib/updateCommitMetadata.js +5 -4
- package/packages/database/src/lib/updateCommitMetadata.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,260 @@
|
|
|
1
|
+
var ii=Object.defineProperty;var Ta=e=>{throw TypeError(e)};var li=(e,t,r)=>t in e?ii(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var pn=(e,t,r)=>li(e,typeof t!="symbol"?t+"":t,r),ci=(e,t,r)=>t.has(e)||Ta("Cannot "+r);var ja=(e,t,r)=>(ci(e,t,"read from private field"),r?r.call(e):t.get(e)),Ia=(e,t,r)=>t.has(e)?Ta("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 di}from"node:stream";import{createReadableStreamFromReadable as ui}from"@react-router/node";import{ServerRouter as hi,useFetcher as Ae,useLocation as zn,useNavigate as It,Link as se,UNSAFE_withComponentProps as $e,Meta as mi,Links as pi,ScrollRestoration as fi,Scripts as gi,useLoaderData as Ye,useRevalidator as rt,Outlet as yi,data as H,useSearchParams as tn,useParams as Ss,useActionData as xi,redirect as bi}from"react-router";import{isbot as vi}from"isbot";import{renderToPipeableStream as wi}from"react-dom/server";import{useState as _,useEffect as ne,useCallback as oe,createContext as Dr,useContext as Bn,useRef as ve,useMemo as ae}from"react";import{Settings as $a,CheckCircle2 as Lr,Bug as Es,AlertTriangle as An,Check as nn,Copy as qt,Loader2 as Ze,HomeIcon as Ci,GitCommitIcon as Ra,File as Ni,RefreshCw as Si,BookOpen as Fr,FlaskConical as Ei,SettingsIcon as Ai,PanelsTopLeftIcon as ki,ComponentIcon as Pi,FileText as Da,Code as La,Box as _i,List as Mi,BarChart3 as Ti,Tag as ji,Image as Kt,Code2 as As,Activity as ur,ChevronDown as ht,CircleEqual as Ii,ArrowLeft as $i,Terminal as kn,Search as rn,ChevronRight as $t,Save as Ri,Pause as ks,ListTodo as Di,PauseCircle as Li,FileCode as Pn,GripVertical as Fi,Ban as Oi,CheckCircle as Yi,FolderOpen as zi,CodeXml as Bi,Zap as Ui,Pencil as Wi,Trash2 as Hi,X as Ps,Folder as _s,Plus as Fa,Eye as Ji,FolderTree as Vi,ChevronsUpDown as Ms,ChevronsDownUp as Ts}from"lucide-react";import"fetch-retry";import Gi from"better-sqlite3";import{Pool as qi}from"pg";import*as Q from"fs";import Et,{existsSync as Mt}from"fs";import*as ee from"path";import le from"path";import{OperationNodeTransformer as Ki,Kysely as js,ParseJSONResultsPlugin as Qi,SqliteDialect as Zi,PostgresDialect as Xi,sql as Ke}from"kysely";import*as el from"kysely/helpers/sqlite";import*as tl from"kysely/helpers/postgres";import _e from"typescript";import*as Ie from"fs/promises";import me,{readdir as Oa,stat as Ya,readFile as Qt,writeFile as Ut,mkdir as nl}from"fs/promises";import*as rl from"os";import Pr from"os";import al from"prompts";import _n from"chalk";import*as sl from"crypto";import Un,{randomUUID as an}from"crypto";import{execSync as Me,spawn as Wn,exec as Or}from"child_process";import{fileURLToPath as Hn}from"url";import{promisify as Yr}from"util";import ol from"dotenv";import il,{EventEmitter as ll}from"events";import{v4 as cl}from"uuid";import dl from"openai";import ul from"p-queue";import za from"p-retry";import{DynamoDBClient as Jn,PutItemCommand as hl}from"@aws-sdk/client-dynamodb";import{LRUCache as zr}from"lru-cache";import"pluralize";import"piscina";import ml from"json5";import{marshall as pl}from"@aws-sdk/util-dynamodb";import fl from"v8";import{Prism as gl}from"react-syntax-highlighter";import{vscDarkPlus as yl}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as xl}from"node:crypto";import{minimatch as Is}from"minimatch";import bl from"react-markdown";import vl from"remark-gfm";import wl from"react-diff-viewer-continued";const $s=5e3;function Cl(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),h=d&&vi(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),$s+1e3);const{pipe:m,abort:p}=wi(n(hi,{context:a,url:e.url}),{[h](){l=!0;const f=new di({final(y){clearTimeout(u),u=void 0,y()}}),g=ui(f);r.set("Content-Type","text/html"),m(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const Nl=Object.freeze(Object.defineProperty({__proto__:null,default:Cl,streamTimeout:$s},Symbol.toStringTag,{value:"Module"}));function Sl({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=_(!1);ne(()=>{i(!0)},[]);const l=oe(()=>{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:o&&a}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:s})]})}const Rs="/assets/cy-logo-cli-CCKUIm0S.svg";function El(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 Al({content:e,className:t=""}){const[r,a]=_(!1),s=oe(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:s,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?c(ce,{children:[n(nn,{size:14}),"Copied"]}):c(ce,{children:[n(qt,{size:14}),"Copy"]})})}function Ds({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=_(""),[l,d]=_(a),[h,u]=_(!1),[m,p]=_(!1),[f,g]=_(null),[y,x]=_(null),v=Ae(),b=v.state!=="idle",w=!!(r.scenarioId||r.analysisId),C=r.analysisId||r.scenarioId||"",N=()=>{const j=`/codeyam:diagnose ${C}`;return o.trim()?`${j} ${o.trim()}`:j};if(v.data&&!m&&!y){const j=v.data;j.success&&j.reportId?(p(!0),g(j.reportId)):j.error&&x(j.error)}const S=async()=>{x(null);const j=new FormData;if(j.append("issueType","other"),j.append("description",o),j.append("email",l),j.append("source",r.source),j.append("entitySha",r.entitySha||""),j.append("scenarioId",r.scenarioId||""),j.append("analysisId",r.analysisId||""),j.append("currentUrl",r.currentUrl),j.append("entityName",r.entityName||""),j.append("entityType",r.entityType||""),j.append("scenarioName",r.scenarioName||""),j.append("errorMessage",r.errorMessage||""),s)try{const O=await(await fetch(s)).blob();j.append("screenshot",O,"screenshot.jpg")}catch(R){console.error("Failed to convert screenshot:",R)}v.submit(j,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),p(!1),g(null),x(null),t()},M=j=>{j.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:M,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:[b?n("div",{className:"animate-spin",children:n($a,{size:24,style:{strokeWidth:1.5}})}):m?n(Lr,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Es,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:k,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?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:k,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):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:El(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&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})]})]})]}),s&&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:s,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:o,onChange:j=>i(j.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:N()}),n(Al,{content:N(),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:j=>d(j.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(An,{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."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.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(An,{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:k,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void S(),disabled:b,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:b?c(ce,{children:[n("div",{className:"animate-spin",children:n($a,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})]})}):null}const Ba={source:"navbar"},Br=Dr(void 0);function kl({children:e}){const[t,r]=_(Ba),a=oe(o=>{r(o)},[]),s=oe(()=>{r(Ba)},[]);return n(Br.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function Xe(e){const t=Bn(Br),r=ve(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 Pl(){const e=Bn(Br),t=zn();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 _l({labs:e}){var C;const t=zn(),r=It(),[a,s]=_(),[o,i]=_(!1),[l,d]=_(!1),[h,u]=_(null),m=Ae();ne(()=>{m.state==="idle"&&!m.data&&m.load("/api/generate-report")},[m]);const p=((C=m.data)==null?void 0:C.defaultEmail)||"",f={width:"20px",height:"20px",strokeWidth:1.5},g=(e==null?void 0:e.simulations)??!0,y=[{id:"dashboard",icon:n(Ci,{style:f}),link:"/",name:"Dashboard",hidden:!g},{id:"simulations",icon:c("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:f,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!g},{id:"git",icon:n(Ra,{style:f}),link:"/git",name:"Git",hidden:!g},{id:"files",icon:n(Ni,{style:f}),link:"/files",name:"Files",hidden:!g},{id:"activity",icon:n(Si,{style:f}),link:"/activity",name:"Activity",hidden:!g},{id:"memory",icon:n(Fr,{style:f}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Ei,{style:f}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Ai,{style:f}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ra,{style:f}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(ki,{style:f}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Pi,{style:f}),link:"/components",name:"Components",hidden:!0}],x=oe(N=>{const S=y.find(k=>k.id===N);S!=null&&S.link&&r(S.link),s(k=>k===N?void 0:N)},[y,r]);ne(()=>{const N={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[S,k]of Object.entries(N))if(k.some(M=>M==="/"?t.pathname==="/":t.pathname.includes(M))){s(S);return}s(void 0)},[t]);const v=async()=>{d(!0);try{const{default:N}=await import("html2canvas-pro"),k=(await N(document.body)).toDataURL("image/jpeg",.8);u(k),i(!0)}catch(N){console.error("Screenshot capture failed:",N),i(!0)}finally{d(!1)}},b=()=>{i(!1),u(null)},w=Pl();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(se,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Rs,alt:"CodeYam",className:"h-6"})})}),y.filter(N=>!N.hidden).map(N=>n(Sl,{id:N.id,selected:N.id===a,onClick:x,icon:N.icon,name:N.name},`sidebar-button-${N.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void v(),disabled:l,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:l?n(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Es,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:l?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),o&&n(Ds,{isOpen:!0,onClose:b,context:w,defaultEmail:p,screenshotDataUrl:h??void 0})]})}const Ls=Dr(void 0);function Ml({children:e}){const[t,r]=_([]),a=oe((o,i="info",l=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,h])},[]),s=oe(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Ls.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function Ur(){const e=Bn(Ls);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Tl({toast:e,onClose:t}){ne(()=>{const s=e.duration||5e3;if(s>0){const o=setTimeout(()=>{t(e.id)},s);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function jl({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(Tl,{toast:r,onClose:t},r.id))]})}function ft(e,t){const[r,a]=_(""),[s,o]=_(!1),[i,l]=_(null),[d,h]=_(!1);ne(()=>{t&&(h(!1),o(!1),l(null))},[t]),ne(()=>{if(!e||!t){t||a("");return}const m=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
|
|
18
|
+
`).filter(b=>b.length>0);if(y.length<3){o(!1),h(!1),l(null),a("");return}const x=y.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];a(b.replace(/.*CodeYam Log Level 1: /,""))}const v=y.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(b),h(!0)}y.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=oe(()=>{a(""),o(!1),l(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function ut({projectSlug:e,onClose:t}){const[r,a]=_("Loading logs..."),[s,o]=_(!0),[i,l]=_(!0),[d,h]=_("all"),u=ve(null);return ne(()=>{const m=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(m().catch(()=>{}),s){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),ne(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[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:m=>h(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:m=>o(m.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:m=>l(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function We({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},a=r[e]||r.other,s=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(As,{size:s,color:a.iconColor});case"visual":return n(Kt,{size:s,color:a.iconColor});case"type":return n(ji,{size:s,color:a.iconColor});case"data":return n(Ti,{size:s,color:a.iconColor});case"index":return n(Mi,{size:s,color:a.iconColor});case"functionCall":return n(La,{size:s,color:a.iconColor});case"class":return n(_i,{size:s,color:a.iconColor});case"method":return n(La,{size:s,color:a.iconColor});case"other":return n(Da,{size:s,color:a.iconColor});default:return n(Da,{size:s,color:a.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Fs({filePath:e,maxLength:t=60,className:r,style:a}){const o=((l,d)=>{if(l.length<=d)return l;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=l.slice(0,m),g=l.slice(-p),y=f.lastIndexOf("/"),x=g.indexOf("/"),v=y>m*.5?f.slice(0,y+1):f,b=x!==-1&&x<p*.5?g.slice(x):g;return`${v}${h}${b}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function hr({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(We,{type:e.entityType||"other"}),c(se,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,s&&o>0&&` (${o})`]}),n(Fs,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const mr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Il({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var J,D,Y;const[d,h]=_(!1),[u,m]=_(!1),[p,f]=_(null),[g,y]=_(new Set),[x,v]=_(new Set),[b,w]=_(!1),C=!!i||o.length>0,N=!!i,S=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),M=(e==null?void 0:e.readyToBeCaptured)??0,j=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(M===0||j>=M);const R=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,O=C,{lastLine:P}=ft(t,O),A=N||o.length>0,T=new Set(((J=i==null?void 0:i.entities)==null?void 0:J.map(L=>L.sha))||[]),F=l.filter(L=>!(L.currentEntityShas||[]).some(E=>T.has(E))),q=(()=>{const I=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&R){const E=e.analysisCompletedAt||e.createdAt;if(new Date(E).getTime()>I)return!0}if(F.length>0){const E=F[0],U=E.analysisCompletedAt||E.archivedAt||E.createdAt;if(U&&new Date(U).getTime()>I)return!0}return!1})();return ne(()=>{const L=(i==null?void 0:i.id)||null;C&&!u&&L!==p&&m(!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:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[A?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(ur,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:A?"Analyzing...":"Activity: No Activity Yet"}),A&&n("button",{onClick:L=>{L.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&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:[A?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(ur,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:A?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(ht,{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:[A&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ur,{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:[(b?S:S.slice(0,3)).map(L=>n(hr,{entity:L,nameSize:"11px",pathSize:"10px",pathMaxLength:150},L.sha)),S.length>3&&n("button",{onClick:()=>w(L=>!L),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:mr,"aria-label":b?"Show fewer entities":`Show ${S.length-3} more entities`,children:b?"Show less":`+${S.length-3} more`}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((L,I)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:L},I)),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"," ",((D=i.entityShas)==null?void 0:D.length)||0," ",((Y=i.entityShas)==null?void 0:Y.length)===1?"entity":"entities","..."]}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]})})]}),o.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Ii,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(L=>{var U,W;const I=g.has(L.id),E=I?L.entities:L.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:L.entities.length>0?c("div",{className:"space-y-1.5",children:[E.map($=>n(hr,{entity:$,nameSize:"10px",pathSize:"9px",pathMaxLength:120},$.sha)),L.entities.length>3&&n("button",{onClick:()=>{y($=>{const K=new Set($);return K.has(L.id)?K.delete(L.id):K.add(L.id),K})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:mr,"aria-label":I?"Show fewer entities":`Show ${L.entities.length-3} more entities`,children:I?"Show less":`+${L.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[L.type==="analysis"&&n(ce,{children:L.entityNames&&L.entityNames.length>0?c("div",{className:"space-y-0.5",children:[L.entityNames.slice(0,5).map(($,K)=>n("div",{children:$},K)),L.entityNames.length>5&&c("div",{className:"italic",children:["+",L.entityNames.length-5," more"]})]}):`Analyzing ${((U=L.entityShas)==null?void 0:U.length)||0} ${((W=L.entityShas)==null?void 0:W.length)===1?"entity":"entities"}`}),L.type==="recapture"&&"Recapturing scenario",L.type==="debug-setup"&&"Setting up debug environment"]})},L.id)})})]}),q&&F.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Lr,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:F.slice(0,3).map((L,I)=>{const E=L.entities||[],U=L.analysisCompletedAt||L.archivedAt||L.createdAt||"",W=(()=>{if(!U)return"";const z=Date.now()-new Date(U).getTime(),B=Math.floor(z/6e4),Z=Math.floor(z/36e5);return Z>0?`${Z}h ago`:B>0?`${B}m ago`:"just now"})(),$=x.has(I),G=($?E:E.slice(0,3)).map(z=>{var B,Z,V;return{...z,scenarioCount:((V=(Z=(B=z.analyses)==null?void 0:B[0])==null?void 0:Z.scenarios)==null?void 0:V.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:E.length>0&&c("div",{className:"space-y-1.5",children:[G.map((z,B)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(hr,{entity:z,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:z.scenarioCount})}),B===0&&W&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:W})]},z.sha)),E.length>3&&n("button",{onClick:()=>{v(z=>{const B=new Set(z);return B.has(I)?B.delete(I):B.add(I),B})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:mr,"aria-label":$?"Show fewer entities":`Show ${E.length-3} more entities`,children:$?"Show less":`+${E.length-3} more`})]})},I)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(se,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(ut,{projectSlug:t,onClose:()=>h(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function sn(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(at):void 0,g=d?At(d):void 0;return He({...m,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function Wr(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 Hr(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:h,...u}=e;return He({...u,branches:t?t.map(Tt):void 0,files:r?r.map(Wr):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function $l(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:l})}function Rl(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:l,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:l,user:h})}function Os(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,h=s?at(s):void 0,u=o?o.map($l):void 0,m=i?i.map(Rl):void 0;return He({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:h,userScenarios:u,comments:m})}function Dl(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?at(e.analysis):void 0,entity:e.entity?sn(e.entity):void 0,branch:e.branch?Tt(e.branch):void 0,createdAt:e.created_at})}function at(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:w,created_at:C,updated_at:N,indirect:S,...k}=e,M=u?sn(u):void 0,j=h?Wr(h):void 0,R=p?Hr(p):void 0,O=m?At(m):void 0,P=f?f.map(Os):void 0,A=g?g.map(Dl):void 0,T=A?A.map(F=>F.branch):void 0;return He({...k,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:M,file:j,commit:O,project:R,scenarios:P,analysisBranches:A,branches:T,dependencyAnalyzedTreeSha:y,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:w,createdAt:C,updatedAt:N,indirect:!!S})}function Jr(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?At(e.commit):void 0,branch:e.branch?Tt(e.branch):void 0})}function Ll(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return He({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function At(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,x=a?Tt(a):void 0,v=i?Tt(i):void 0,b=(s==null?void 0:s.length)>0?Ll(s[s.length-1]):void 0,w=(u??[]).map(at),C=(m??[]).map(sn),N=(p==null?void 0:p.length)>0?p.map(Jr):void 0;return h&&(h.username=h.preferredUsername??h.username),He({...y,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:l,htmlUrl:d,author:h,analyses:w,entities:C,commitBranches:N,committedAt:f,analyzedAt:g})}function Tt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:l,primary:d,...h}=e,u=a?a.map(At):void 0,m=s?s.flatMap(p=>at(p.analysis)):void 0;return He({...h,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}var Yn;class Fl{constructor(){Ia(this,Yn,new Ol)}transformQuery(t){return ja(this,Yn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Yn=new WeakMap;class Ol extends Ki{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 te=()=>null,Yl={analyzed_at:te(),configuration:te(),content_changed_at:te(),created_at:te(),description:te(),github_token:te(),id:te(),metadata:te(),name:te(),path:te(),slug:te(),team_id:te(),updated_at:te()},zl=Object.keys(Yl),Bl={active:te(),analysis_id:te(),branch_id:te(),created_at:te(),entity_sha:te(),id:te()},Ul=Object.keys(Bl),Wl={active_at:te(),content_changed_at:te(),created_at:te(),id:te(),metadata:te(),name:te(),primary:te(),project_id:te(),ref:te(),sha:te(),updated_at:te()},Ys=Object.keys(Wl),Hl={ai_message:te(),analyzed_at:te(),author_github_username:te(),branch_id:te(),committed_at:te(),created_at:te(),files:te(),html_url:te(),id:te(),merged_branch_id:te(),message:te(),metadata:te(),project_id:te(),sha:te(),title:te(),url:te()},zs=Object.keys(Hl);zs.filter(e=>e!=="files");const Jl={commit_id:te(),created_at:te(),description:te(),documentation:te(),entity_type:te(),file_id:te(),file_path:te(),metadata:te(),name:te(),project_id:te(),quality:te(),sha:te(),updated_at:te()},Bs=Object.keys(Jl),Vl={active:te(),branch_id:te(),entity_sha:te()},Gl=Object.keys(Vl),ql={created_at:te(),deleted:te(),id:te(),metadata:te(),name:te(),path:te(),project_id:te(),updated_at:te()},Kl=Object.keys(ql),Ql={analysis_id:te(),approved:te(),created_at:te(),description:te(),id:te(),metadata:te(),name:te(),previous_version_id:te(),project_id:te()},Mn=Object.keys(Ql),Zl=!!kt("ENABLE_QUERY_LOGGING"),Xl=!!kt("ENABLE_QUERY_ERROR_LOGGING");kt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let fn;function Ce(){if(!fn){const e=Ws();if(e==="sqlite")fn=ec();else if(e==="postgresql")fn=tc();else throw new Error(`Unknown database type: ${e}`)}return fn}function ec(e){if(e||(e=kt("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(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new Gi(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const s=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&s.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(s){console.error("CodeYam DB ERROR: Failed to verify database schema:",s)}return new js({dialect:new Zi({database:a}),plugins:[new Qi,new Fl],log:Us})}function tc(){const e=rc();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new qi({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new js({dialect:new Xi({pool:t}),log:Us})}let pr=null;function Pt(){return pr||(pr=nc(Ws())),pr}function Us(e){e.level==="error"?Xl&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Zl&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function nc(e){if(e==="sqlite")return el;if(e==="postgresql")return tl;throw new Error(`Unknown database type: ${e}`)}function Ws(){if(kt("SQLITE_PATH"))return"sqlite";if(kt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function rc(){const e=kt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function kt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var on=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(on||{});const Vn="Default Scenario";let ac="<main>";function sc(){return ac}function Ua(e,...t){ge(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function ge(...e){const t=sc(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
|
|
21
|
+
${s.stack}`:typeof s=="object"?oc(s):String(s)}).filter(Boolean).join(`
|
|
22
|
+
`),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
23
|
+
`);return}console.log(a.replace(/\n/g,"\r"))}function oc(e,t=2){function r(a,s=new WeakMap){return a===null||typeof a!="object"?a:s.has(a)?`"[Circular: ${a.constructor.name}]"`:(s.set(a,!0),Array.isArray(a)?`[${a.map(l=>{const d=r(l,s);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,s):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const s=r(e);if(!t)return s;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:a,serialized:s}),s}}}function Tn(e,t){try{let r=function(o){var i,l;if(_e.isFunctionDeclaration(o)&&Bt(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(a),u=fr(o);s.push({name:d,code:h,sha:bt(t,d,h),entityType:"function",isDefault:u})}else if(_e.isClassDeclaration(o)&&Bt(o)){const d=((l=o.name)==null?void 0:l.text)||"default",h=o.getText(a),u=fr(o),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");s.push({name:d,code:h,sha:bt(t,d,h),entityType:m?"component":"class",isDefault:u})}else if(_e.isInterfaceDeclaration(o)&&Bt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:bt(t,d,h),entityType:"interface",isDefault:!1})}else if(_e.isTypeAliasDeclaration(o)&&Bt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:bt(t,d,h),entityType:"type",isDefault:!1})}else if(_e.isVariableStatement(o)&&Bt(o)){const d=fr(o);o.declarationList.declarations.forEach(h=>{var u;if(_e.isIdentifier(h.name)){const m=h.name.text,p=o.getText(a),f=((u=h.initializer)==null?void 0:u.getText(a))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:m,code:p,sha:bt(t,m,p),entityType:g?"component":"variable",isDefault:d})}})}else if(_e.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:bt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(_e.isExportDeclaration(o)&&o.exportClause&&_e.isNamedExports(o.exportClause)){const d=o.getText(a);for(const h of o.exportClause.elements){const u=h.name.text;s.push({name:u,code:d,sha:bt(t,u,d),entityType:"unknown",isDefault:!1})}}_e.forEachChild(o,r)};const a=_e.createSourceFile(t,e,_e.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Bt(e){if(!_e.canHaveModifiers(e))return!1;const t=_e.getModifiers(e);return t?t.some(r=>r.kind===_e.SyntaxKind.ExportKeyword):!1}function fr(e){if(!_e.canHaveModifiers(e))return!1;const t=_e.getModifiers(e);return t?t.some(r=>r.kind===_e.SyntaxKind.DefaultKeyword):!1}function bt(e,t,r){const a=Un.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function ic(e){var h;const{webapp:t,port:r,environmentVariables:a,packageManager:s}=e,o=t==null?void 0:t.startCommand;if(!o)return`${s} ${s==="npm"?"run ":""}dev`;const i=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of a)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function lc(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=ee.normalize(e),a=[...t].sort((s,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=s.path)==null?void 0:l.length)??0)});for(const s of a){const o=ee.normalize(s.path??".");if(o==="."||r.startsWith(o+ee.sep)||r===o)return s}return t[0]}function cc(e){const{filePath:t,webapps:r,environmentVariables:a,port:s,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=lc(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=ic({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${s}/static/codeyam-sample`}}function Gn(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}function dc(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 uc({ids:e,analysisId:t}){const r=Ce();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw ge("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 ge("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function hc(...e){try{const t=Un.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 gr(e,t){return t.map(r=>mc(e,r))}function mc(e,t){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(t)}function pc(e,t,r){return t.map(a=>fc(e,a,r))}function fc(e,t,r){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(`_cy_${r}:${t}`)}function gc(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const yc=50;function xc(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 Wa({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:d}){const h=Ce(),{jsonObjectFrom:u,jsonArrayFrom:m}=Pt();let p=d?h.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return a&&(p=p.where("entity_name","=",a)),s&&(p=p.where("entity_sha","in",s)),i&&(p=p.where("branch_commit_sha","=",i)),l&&(p=p.limit(l)),d?h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(gr("scenarios",Mn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(gr("entities",Bs)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(gr("scenarios",Mn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function mt(e){const{ids:t,fileIds:r,entityShas:a,commitIds:s}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:s,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let l=[];if(i){const[d,{arr:h,key:u}]=i,m=xc(h,yc),p=[];for(let f=0;f<m.length;f++){const g=m[f],x=await Wa({...e,[u]:g}).execute();x&&p.push(...x)}l=p}else{const h=await Wa(e).execute();if(!h||h.length===0)return ge("CodeYam: No analyses found",null,e),null;l=h}return l.length===0?null:l.map(at)}catch(o){return ge("CodeYam Error: Database error in loadAnalyses",o,e),null}}function bc(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=Pt();let s=e.selectFrom("analysis_branches").select(Ul).select(o=>a(o.selectFrom("branches").select(Ys).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function st({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=Ce(),g=Date.now();try{let y=f.selectFrom("analyses").selectAll("analyses");e&&(y=y.where("id","=",e)),r&&(y=y.where("project_id","=",r)),i?y=y.where("dependency_analyzed_tree_sha","=",i):l?y=y.where("analyzed_tree_sha","=",l):a&&(y=y.where("file_id","=",a)),o&&(y=y.where("entity_name","=",o)),s?y=y.where("commit_id","=",s):y=y.orderBy("created_at","desc").limit(1),t&&(y=y.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=Pt();y=y.select(C=>{const N=[];return N.push(x(C.selectFrom("entities").select(Bs).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&N.push(x(C.selectFrom("files").select(Kl).whereRef("files.id","=","analyses.file_id")).as("file")),h&&N.push(x(C.selectFrom("projects").select(zl).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&N.push(v(C.selectFrom("scenarios").select(Mn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&N.push(bc(C,S=>S.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&N.push(x(C.selectFrom("commits").select(zs).select(S=>dc(S).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),N});const b=await y.executeTakeFirst(),w=Date.now()-g;if(!b)return ge("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null;if(w>100&&u){const C=b.commit,N=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${w}ms (files: ${Math.round(N/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return at(b)}catch(y){return ge("CodeYam Error: Database error loading analysis",y,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function Hs({projectId:e,ids:t,names:r,includeInactive:a}){const s=Ce();try{let o=s.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return a||(o=o.where("active_at","is not",null)),(await o.execute()).map(Tt)}catch(o){return ge("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function vc({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=Ce();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,h=>h.select(pc("branches",Ys,"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(h=>gc(h,"branch")).map(Jr)}catch(i){return ge("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function wc(e){if(e.length===0)return new Map;const t=Ce();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(o=>{o.branch_id&&a.add(o.branch_id),o.merged_branch_id&&a.add(o.merged_branch_id)}),a.size===0)return new Map;const s=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(s.map(o=>[o.id,o]))}catch(r){return ge("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Cc(e){if(e.length===0)return new Map;const t=Ce(),{jsonObjectFrom:r,jsonArrayFrom:a}=Pt();try{const s=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(Mn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(s){return ge("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function Nc(e){if(e.length===0)return new Map;const t=Ce();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(s=>{const o=a.get(s.commit_id)||[];o.push(s),a.set(s.commit_id,o)}),a}catch(r){return ge("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function jn({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=Ce(),{jsonObjectFrom:d}=Pt(),h=Date.now();try{let u=l.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(s&&s.length>0){const b=Ke.join(s.map(w=>Ke`${w}`),Ke`, `);u=u.where(Ke`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${Ke.ref("commits.files")}) AS f
|
|
27
|
+
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
+
)
|
|
29
|
+
`)}t&&(u=u.where("branch_id","=",t));const m=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-h;if(!m||m.length===0)return[];if(p>100){const b=m.reduce((w,C)=>w+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${m.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return m.map(w=>({...w,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(At);const f=m.map(b=>b.id),[g,y,x]=await Promise.all([wc(f),Cc(f),Nc(f)]);return m.map(b=>{const w=b.branch_id?g.get(b.branch_id):void 0,C=b.merged_branch_id?g.get(b.merged_branch_id):void 0,N=y.get(b.id)||[],S=x.get(b.id)||[];return{...b,branch:w,mergedBranch:C,analyses:N,entities:S}}).map(At)}catch(u){return ge("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function pt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o,excludeMetadata:i}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let h=0;h<o.length;h+=50){const u=o.slice(h,h+50),m=await pt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:u,excludeMetadata:i});m&&d.push(...m)}return d}const l=Ce();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!s,m=>m.where("entities.name","in",s)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):u.map(sn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function Sc(e,t){const{jsonArrayFrom:r}=Pt();let a=e.selectFrom("entity_branches").select(Gl);return t&&(a=t(a)),r(a)}async function Js({projectId:e,sha:t}){const r=Ce();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>Sc(s,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?sn(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&ge("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return ge("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const yr=1e3;async function Vs({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 h=t.slice(d,d+50),u=await Vs({projectId:e,filePaths:h,fileIds:r,fileNames:a});u&&l.push(...u)}return l}const s=Ce(),o=[];let i=0;try{for(;;){let l=s.selectFrom("files").selectAll().where("project_id","=",e).limit(yr).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(a){if(a.length===0)return[];l=l.where("name","in",a)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<yr))break;i+=yr}return o==null?void 0:o.map(Wr)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Ec({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=Ce().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=Hr(l);return a&&(d.files=await Vs({projectId:d.id})),r&&(d.branches=await Hs({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function In(e,t){const r={...e};for(const a in t){const s=t[a],o=e[a];s!=null&&typeof s=="object"&&!Array.isArray(s)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[a]=In(o,s):s!==void 0&&(r[a]=s)}return r}async function dt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await Ce().transaction().execute(async i=>{var u,m;const l=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!l)return ge(`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:",s)),r=In(r??{},{currentRun:a});else if(!r&&!o)return d;const h=r?In(d,r):d;if(s&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((m=h.historicalRuns)==null?void 0:m.length)||0}`);const p={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),h.historicalRuns=[...h.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(h);try{return await i.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",l.id).returning(["id"]).executeTakeFirst()?h:(ge(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return ge(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return ge(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function Gs(e,t,r="analysis"){try{return await Ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return ge(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=at(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(ge(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return ge(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Rt(e,t,r="capture"){try{return await Ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return ge(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=at(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(ge(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return ge(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function qs({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Ce().transaction().execute(async s=>{const o=await s.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return ge(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const l=r?In(i,r):i;a&&await a(l,Hr(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(ge(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return ge(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return ge(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}function Ac(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??an(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function kc(e){if(e.length===0)return[];const t=Ce(),r=e.map(Ac);try{return(await t.insertInto("scenarios").values(r).onConflict(Gn(r[0],"id",["created_at"])).returningAll().execute()).map(Os)}catch(a){return ge("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function Pc(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??an(),commit_id:r,branch_id:a}}async function Ha(e){if(e.length===0)return[];const t=Ce(),r=e.map(Pc);try{return(await t.insertInto("commit_branches").values(r).onConflict(Gn(r[0],"id",["created_at"])).returningAll().execute()).map(Jr)}catch(a){return ge("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function _c(e,t){const r=Ce(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(Gn(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return ge("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}function Mc(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:h,author:u,metadata:m,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??an(),project_id:a??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:h}}async function Tc({projectId:e,commits:t}){const r=Ce();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 _c(i,a[i]);const s=t.map(i=>Mc(i,e));return(await r.insertInto("commits").values(s).onConflict(Gn(s[0],"id",["created_at"])).returningAll().execute()).map(At)}catch(a){return ge("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const $n=ee.join(rl.homedir(),".codeyam","secrets.json"),Rn=ee.join(process.cwd(),".codeyam","secrets.json");async function gt(){let e={};try{if(Q.existsSync(Rn)){const o=await Ie.readFile(Rn,"utf8");e=JSON.parse(o)}}catch{console.warn(_n.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(Q.existsSync($n)){const o=await Ie.readFile($n,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(_n.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(t.ANTHROPIC_API_KEY=a);const s=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return s&&(t.GROQ_API_KEY=s),t}async function jc(e,t=!0){const r=t?$n:Rn,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 Ic(e=!0){return e?$n:Rn}async function Ja(){const e=await gt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function $c(e){console.log(),console.log(_n.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await al({type:"password",name:"key",message:"OpenAI API Key",validate:s=>s&&!s.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function Rc(e=!0){const t=await Ja();if(t.isValid)return t.secrets;const r=await $c(t.missing),s={...await gt(),...r};await jc(s,e);const o=Ic(e);return console.log(_n.green(`✓ Configuration saved to ${o}`)),(await Ja()).secrets}function Ks(e=process.cwd()){let t=ee.resolve(e);const r=ee.parse(t).root;for(;t!==r;){const s=ee.join(t,".codeyam","config.json");if(Q.existsSync(s))return t;t=ee.dirname(t)}const a=ee.join(r,".codeyam","config.json");return Q.existsSync(a)?r:null}let Qs=Ks();function pe(){return Qs}function Dc(e){Qs=e}function Zs(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const Lc={"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>`};Zs(Lc);const Fc={"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>`};Zs(Fc);function Wt(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Wt(s[i],l,r):o[i]=l}return o}const a={...e};for(const s in t)if(t[s]===null)a[s]=null;else if(Array.isArray(t[s])){const o=Array.isArray(e[s])?e[s]:[];a[s]=[];for(let i=0;i<t[s].length;i++){const l=t[s][i];typeof l=="object"&&l!==null?a[s][i]=Wt(o[i],l,r):a[s][i]=l}}else typeof t[s]=="object"&&t[s]!==null?a[s]=Wt(a[s]??{},t[s],r):a[s]=t[s];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function Oc({projectId:e,commit:t,branch:r}){var l,d,h,u,m,p,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await vc({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(l=o.sort((y,x)=>{var v,b,w,C;return(((b=(v=y.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.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&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=a.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?a=r:s.active=!1);const g=o.filter(y=>y.active&&y.branch.id!==a.id||!y.active&&y.branch.id===a.id);g.length>0&&await Ha(g.map(y=>({...y,active:y.branchId===a.id})))}(o==null?void 0:o.find(g=>g.branchId===s.branchId))||await Ha([s])}function yt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=pe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return le.join(e,".codeyam","db.sqlite3")}async function Re(){const e=await Rc();process.env.SQLITE_PATH=yt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Te(e){await Re();const t=await Ec({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await Hs({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 Yc(e,t,r){await Re();const a=pe(),s=hc(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(a)try{if(h=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
|
|
30
|
+
`);h=`@@ -0,0 +1,${m.length} @@
|
|
31
|
+
${m.map(p=>`+${p}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:s,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${s}`,htmlUrl:`local://codeyam/${e.slug}/${s}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await Tc({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await Oc({projectId:e.id,commit:l[0],branch:t}),l[0]}async function ln(){await Re();const e=await pt({excludeMetadata:!0});if(!e||e.length===0)return[];const t=e.filter(d=>{var h;return!((h=d.metadata)!=null&&h.isSuperseded)}),r=t.map(d=>d.sha),a=t.map(d=>{var h;return(h=d.metadata)==null?void 0:h.previousVersionWithAnalyses}).filter(d=>!!d),s=[...new Set([...r,...a])],o=await mt({entityShas:s,excludeMetadata:!0}),i=new Map;if(o)for(const d of o)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return t.map(d=>{var m;const h=i.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=(m=d.metadata)==null?void 0:m.previousVersionWithAnalyses;if(u){const p=i.get(u)||[];return{...d,analyses:p}}return{...d,analyses:[]}})}async function qn(e,t){await Re();const r=await mt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await Js({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function Vr(e){if(await Re(),e.name&&e.projectId){const r=await mt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0];const s=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0]}}const t=await mt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function Xs(e){await Re();const t=await mt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function jt(e){await Re();const t=await De();if(!t)return null;const{project:r}=await Te(t);return await Js({projectId:r.id,sha:e})}async function eo(e){var a,s,o,i,l,d,h,u;await Re();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=await pt({projectId:e.projectId,filePaths:[p.filePath],names:[p.name]});if(f&&f.length>0){const g=f[0],y=await mt({entityShas:[g.sha],limit:1});let x,v,b;if(y&&y.length>0&&y[0].scenarios){const w=y[0],C=w.scenarios||[],N=C.length,S=C.find(M=>{var j,R;return(R=(j=M.metadata)==null?void 0:j.screenshotPaths)==null?void 0:R[0]});S&&(x=(o=(s=S.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],v=S.name),b={status:((i=g.metadata)==null?void 0:i.previousVersionWithAnalyses)||w.entitySha!==g.sha?"out_of_date":"up_to_date",scenarioCount:N,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 b={status:"not_analyzed"};t.push({...g,screenshotPath:x,scenarioName:v,analysisStatus:b})}}}if((l=e.metadata)!=null&&l.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const g=e.metadata.importedBy[p][f];g.shas&&m.push(...g.shas)}if(m.length>0){const p=await pt({projectId:e.projectId,shas:m});if(p)for(const f of p){const g=await mt({entityShas:[f.sha],limit:1});let y,x,v;if(g&&g.length>0&&g[0].scenarios){const b=g[0],w=b.scenarios||[],C=w.length,N=w.find(k=>{var M,j;return(j=(M=k.metadata)==null?void 0:M.screenshotPaths)==null?void 0:j[0]});N&&(y=(h=(d=N.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],x=N.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function De(){try{const e=pe();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await me.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Dt(){await Re();try{const e=await De();if(!e)return null;const{project:t,branch:r}=await Te(e),a=await jn({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Gr(){try{const e=pe();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await me.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function to(e){try{const t=pe();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=le.join(t,e.filePath);return await me.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function no(e){try{const t=pe();if(!t||!e.filePath)return!1;const r=le.join(t,e.filePath),s=(await me.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return s>i+1e3}catch{return!1}}async function ro(e){if(await Re(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await pt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await mt({entityShas:r}),s=new Map;if(a)for(const i of a)s.has(i.entitySha)||s.set(i.entitySha,[]),s.get(i.entitySha).push(i);for(const[i,l]of s.entries())l.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,l)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=l.analyses[0])==null?void 0:m.createdAt)||l.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function ao(e){try{const t=pe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=le.join(t,".codeyam","config.json"),a=await me.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await me.writeFile(r,i,"utf8"),s.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await qs({projectSlug:s.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const zc=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:ln,getAnalysesForEntity:qn,getAnalysisForExactEntitySha:Xs,getCurrentCommit:Dt,getEntityBySha:jt,getEntityCodeFromFilesystem:to,getEntityHistory:ro,getLatestAnalysisForEntity:Vr,getProjectConfig:Gr,getProjectSlug:De,getRelatedEntities:eo,hasFileBeenModifiedSinceEntity:no,requireBranchAndProject:Te,updateProjectConfig:ao},Symbol.toStringTag,{value:"Module"})),so="secrets.json";function oo(e){return le.join(e,".codeyam",so)}function io(){return le.join(Pr.homedir(),".codeyam",so)}async function Kn(e){let t={};try{const r=io(),a=await me.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=oo(e),a=await me.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function Bc(e,t,r=!0){const a=r?io():oo(e),s=le.dirname(a);await me.mkdir(s,{recursive:!0}),await me.writeFile(a,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}async function Uc(e){const t=await Kn(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 Wc({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){return new Promise((i,l)=>{const d=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...o);for(const f of r)u.push(`--exclude=${f}`);u.push(d,h);const m=Date.now(),p=Wn("rsync",u);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-m)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),l(f)})})}const Hc=Yr(Or);async function Jc(e){return new Promise(t=>setTimeout(t,e))}function Vc(e){try{return process.kill(e,0),!0}catch{return!1}}async function lo(e){try{const{stdout:t}=await Hc(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
+
`).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await lo(s);a.push(...o)}return a}catch{return[]}}function Va(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function Gc(e,t,r){const a=await lo(e);for(const s of a.reverse())await Va(s,t,r);await Va(e,t,r)}async function Zt(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function s(o,i){await Gc(e,o,t);for(let l=0;l<i;l++)if(await Jc(1e3),a+=1e3,!await Vc(e))return t(`Process tree ${e} successfully killed with ${o} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await s("SIGINT",5)||await s("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await s("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function qc(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:xl(),createdAt:t}}ol.config({quiet:!0});var co=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(co||{});class Kc extends il{constructor(){super(...arguments),this.processes=new Map}register(t){const r=cl(),{process:a,type:s,name:o,metadata:i,parentId:l}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const m=this.processes.get(l);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const h=(m,p)=>{this.handleProcessExit(r,m,p)},u=m=>{this.handleProcessError(r,m)};return a.on("exit",h),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",h),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(l=>this.shutdown(l,r))),o.pid)try{await Zt(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),s.state==="running"&&(s.state="killed",s.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(s=>this.shutdown(s.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[s,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(s)}}}handleProcessExit(t,r,a){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.exitCode=r,o.signal=a,r===0?o.state="completed":a?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:s}=a;s.endedAt=Date.now(),s.state="failed",s.metadata={...s.metadata,error:r.message},this.emit("processExited",s)}}let xr=null;function Qc(){return xr||(xr=new Kc),xr}const Zc={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Xc({command:e,args:t,workingDir:r,outputOptions:a=Zc,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},l=Wn(e,t,{cwd:r,env:i});return Qc().register({process:l,type:co.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const g=le.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(v=>v.trim()?`[${y}]${g} ${v}`:v).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&&m(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&&m(y+`
|
|
38
|
+
`),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function ed(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 td({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
+
`);Q.writeFileSync(`${e}/.env`,s);const o=ed(r);return Xc({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const nd="/tmp/codeyam/local-dev";function uo(e){return ee.join(nd,e)}function ho(e){return ee.join(uo(e),"codeyam")}function ot(e){return ee.join(uo(e),"project")}function Qn(e){return ee.join(ho(e),"log.txt")}const rd=[".sync-metadata.json","__codeyamMocks__"];async function ad(e,t={}){const{port:r,silent:a=!0}=t,s=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 "${s}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function sd(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=ot(e),i=[],l=[];if(!Q.existsSync(o))return{removed:i,errors:l};r&&await ad(e,{port:a,silent:s});for(const d of rd){const h=ee.join(o,d);if(Q.existsSync(h))try{(await Ie.stat(h)).isDirectory()?await Ie.rm(h,{recursive:!0,force:!0}):await Ie.unlink(h),i.push(d)}catch(u){l.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const od=ee.dirname(Hn(import.meta.url));function id(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 qr(){const e=id(od);return ee.join(e,"analyzer-template")}function Lt(e){return ho(e)}async function Ga(e){const t=qr(),r=Lt(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 Wc({sourcePath:t,destinationPath:r,silent:!0})}function Ft(e,t,r,a){const s=Lt(e);if(!Q.existsSync(s))throw new Error(`Analyzer not found at ${s}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return td({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function ld(e){const t=qr(),r=Lt(e),a=ee.join(t,".build-info.json"),s=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(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(Q.readFileSync(a,"utf8")),i=JSON.parse(Q.readFileSync(s,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function cn(e,t){const r=Lt(e);if(!Q.existsSync(r)){t.update("Creating analyzer..."),await Ga(e);return}const a=ld(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await Ga(e))}async function Kr(e){await sd(e,{killProcesses:!1})}const cd=ee.dirname(Hn(import.meta.url));function mo(){let e=cd;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 Vt(e){if(!Q.existsSync(e))return null;try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function dd(){const e=mo();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=Vt(r);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}const Qr=dd();function po(e){const t=mo();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 h of d)if(r=Vt(h),r)break}const a=qr(),s=ee.join(a,".build-info.json"),o=Vt(s);let i=null;if(e){const d=Lt(e),h=ee.join(d,".build-info.json");i=Vt(h)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:Qr,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function Zn(e){const t=Lt(e),r=ee.join(t,".build-info.json"),a=Vt(r);return(a==null?void 0:a.version)??null}function fo(){const e=pe();return e?ee.join(e,".codeyam","server.json"):null}function go(){const e=fo();if(!e||!Q.existsSync(e))return null;try{const t=Q.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function ud(){const e=fo();if(e)try{Q.unlinkSync(e)}catch{}}const hd="/assets/globals-Bh6jH0cL.css";function md({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=_(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(se,{to:a,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function pd({serverVersion:e}){const[t,r]=_("stale"),[a,s]=_(null),o=async()=>{r("restarting"),s(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<d?setTimeout(()=>void u(),h):(s("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){s(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children: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 o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&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 Dn(e){return ee.join(e,".codeyam","queue.json")}function Ht(e){const t=Dn(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 fd(e,t){const r=Dn(e),a=ee.dirname(r);Q.existsSync(a)||Q.mkdirSync(a,{recursive:!0});try{Q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function gd(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await yd(e,t,r);else if(e.type==="baseline")await xd(e,t,r);else if(e.type==="recapture")await bd(e,t,r);else if(e.type==="capture-only")await vd(e,t,r);else if(e.type==="debug-setup")await wd(e,t,r);else if(e.type==="interactive-start")await Cd(e,t,r);else if(e.type==="interactive-stop")await Nd(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 yd(e,t,r){var y,x,v,b;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:l}=await Te(a);await Kr(a),await cn(a,{update:w=>console.log(`[Queue] ${w}`)});const d=Zn(a),h={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(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 m=e.onlyDataStructure,p={packageManager:((v=l.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=Ft(a,h,p),g=w=>{try{return process.kill(w,0),!0}catch{return!1}};await dt({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const w=new Promise((C,N)=>setTimeout(()=>N(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,w]),await dt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await dt({commitSha:s,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 Zt(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 Zt(f.process.pid,()=>{})}catch{}try{await dt({commitSha:s,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 xd(e,t,r){var p,f,g;const{projectSlug:a,commitSha:s}=e;if(!s)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:o}=await Te(a);await Kr(a),await cn(a,{update:y=>console.log(`[Queue] ${y}`)});const i=Zn(a),l={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((g=o.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=Ft(a,l,h),m=y=>{try{return process.kill(y,0),!0}catch{return!1}};await dt({commitSha:s,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await dt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await Zt(u.process.pid,()=>{})}catch{}}}async function bd(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const l=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-C0KrUQp-.js"),b=v(),w=await b.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 b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await Rt(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Te(a);await cn(a,{update:v=>console.log(`[Queue] ${v}`)});const h=Zn(a),u={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={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)??on.Next,orchestrateCapture:"local-sequential"},p=Ft(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function vd(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const l=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-C0KrUQp-.js"),b=v(),w=await b.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 b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await Rt(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Te(a);await cn(a,{update:v=>console.log(`[Queue] ${v}`)});const h=Zn(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={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)??on.Next,orchestrateCapture:"local-sequential"},p=Ft(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function wd(e,t,r){var p,f,g,y;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Debug setup job missing analysisId");const i=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Te(a);await Kr(a),await cn(a,{update:x=>console.log(`[Queue] ${x}`)});const d={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={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)||on.Next},m=await Ft(a,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function Cd(e,t,r){var m,p,f,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Te(a),d={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((m=l.metadata)==null?void 0:m.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)||on.Next};await Rt(s,y=>{y.readyToBeCaptured=!0});const u=Ft(a,d,h);await Gs(s,y=>{y.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${s}, PID: ${u.process.pid}`)}async function Nd(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${s} not found`);const i=(d=o.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${s}`);return}const l=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${l}`);try{try{process.kill(l,0)}catch{console.log(`[Queue] Process ${l} already exited`);return}await Zt(l,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${l}`)}catch(h){throw console.error(`[Queue] Failed to kill process ${l}:`,h),h}finally{await Gs(s,h=>{h.interactiveMode=null})}}class Sd{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=Ht(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||an(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(s=>s.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const s=this.completionCallbacks.get(t);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const s=r==="up"?a-1:a+1;if(s<0||s>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[s],this.state.jobs[s]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${s})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await gd(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(){fd(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Ed{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=Dn(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=Dn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=Q.watch(r,(a,s)=>{s==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=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 Ad{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=Ht(r)}start(){this.cachedState=Ht(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 Ed(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const s=new Promise((i,l)=>{r=i,a=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:o,completion:s}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Ht(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Ht(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 kd(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 Pd(e){try{return process.kill(e,0),!0}catch{return!1}}async function _d(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 Md(e){const t=kd(e);return!t||!Pd(t.pid)||!await _d(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Td extends ll{constructor(){super();pn(this,"watcher",null);pn(this,"dbPath",null);pn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=yt();const{default:r}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",s=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${s}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",s=>{console.error("Database watcher error:",s),this.emit("error",s)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const a=Date.now(),s=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${s} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const _r=new Td;let Nt=null,Jt=null;async function jd(){if(!Nt){if(Jt){await Jt;return}Jt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Ks()||process.cwd();Dc(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await Md(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Ad(t,e,()=>{_r.notifyChange("unknown")});await r.start(),Nt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Sd(e,_r);await r.start(),Nt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Jt}}async function it(){return Nt||await jd(),Nt}function Id(){return Nt||(Jt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const $d=()=>[{rel:"stylesheet",href:hd},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function Rd({request:e,context:t}){var r,a,s,o,i,l,d,h;try{const u=pe()||process.cwd(),[m,p]=await Promise.all([De(),Kn(u)]);if(!m)throw new Error("Project slug not found");const{project:f,branch:g}=await Te(m),y=await jn({projectId:f.id,branchId:g.id,limit:20,skipRelations:!0}),x=y.length>0?y[0]:null,v=t.analysisQueue||Id(),b=v==null?void 0:v.getState(),w=async D=>{if(!D||D.length===0)return[];const Y=Math.min(Math.max(D.length*2e3,1e4),6e4),L=new Promise(E=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${Y}ms for ${D.length} entities`),E([])},Y)),I=pt({shas:D,excludeMetadata:!0}).then(E=>E||[]);return Promise.race([I,L])},C=await Promise.all(((b==null?void 0:b.jobs)||[]).map(async D=>{var L;const Y=await w(D.entityShas||[]);return Y.length===0&&((L=D.entityShas)!=null&&L.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",D.id),{...D,entities:Y}}));let N=null;if(b!=null&&b.currentlyExecuting){const D=b.currentlyExecuting,Y=await w(D.entityShas||[]);Y.length===0&&((r=D.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",D.id),N={...D,entities:Y}}const S=N?C.filter(D=>D.id!==N.id):C;let k=((s=(a=x==null?void 0:x.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(k.length===0){const D=((o=x==null?void 0:x.metadata)==null?void 0:o.historicalRuns)||[];if(D.length>0){const L=[...D].sort((I,E)=>{const U=I.archivedAt||I.createdAt||"";return(E.archivedAt||E.createdAt||"").localeCompare(U)})[0];if(L){const I=L.analysisCompletedAt||L.createdAt;if(I){const E=new Date(I).getTime(),W=Date.now()-1440*60*1e3;E>W&&(k=L.currentEntityShas||[])}}}}const M=await w(k),j=[];p.ANTHROPIC_API_KEY&&j.push("ANTHROPIC_API_KEY"),p.GROQ_API_KEY&&j.push("GROQ_API_KEY"),p.OPENAI_API_KEY&&j.push("OPENAI_API_KEY"),p.OPENROUTER_API_KEY&&j.push("OPENROUTER_API_KEY");const R=[];for(const D of y){const Y=((i=D.metadata)==null?void 0:i.historicalRuns)||[];for(const L of Y){const I=L.currentEntityShas||[];if(I.length>0){const E=await w(I);R.push({...L,entities:E})}else R.push(L)}}const O=R.sort((D,Y)=>{const L=D.archivedAt||D.analysisCompletedAt||D.createdAt||"";return(Y.archivedAt||Y.analysisCompletedAt||Y.createdAt||"").localeCompare(L)}),P=new Set(((l=N==null?void 0:N.entities)==null?void 0:l.map(D=>D.sha))||[]),A=O.filter(D=>!(D.currentEntityShas||[]).some(L=>P.has(L))),T=go(),F=(T==null?void 0:T.cliVersion)??"unknown",q=F!=="unknown"&&F!==Qr,J={currentRun:(d=x==null?void 0:x.metadata)==null?void 0:d.currentRun,projectSlug:m,currentEntities:M,availableAPIKeys:j,queuedJobCount:S.length,queueJobs:S,currentlyExecuting:N,historicalRuns:A,isServerOutOfDate:q,serverVersion:F,labs:((h=f.metadata)==null?void 0:h.labs)??null};return H(J)}catch(u){return console.error("Failed to load root data:",u),H({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",labs:null})}}function Dd(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:d,serverVersion:h,labs:u}=Ye(),{toasts:m,closeToast:p}=Ur(),f=rt(),g=ve(f),y=zn();ne(()=>{g.current=f},[f]);const x=y.pathname.startsWith("/entity/")&&y.pathname.includes("/edit/")||y.pathname.startsWith("/dev/"),v=y.pathname.includes("/fullscreen");return ne(()=>{const b=new EventSource("/api/events");let w=null,C=0;const N=2e3;return b.addEventListener("message",S=>{const k=JSON.parse(S.data);if(k.type==="queue")g.current.revalidate(),C=Date.now();else if(k.type==="db-change"||k.type==="unknown"){const M=Date.now(),j=M-C;j<N?(w&&clearTimeout(w),w=setTimeout(()=>{g.current.revalidate(),C=Date.now(),w=null},N-j)):(g.current.revalidate(),C=M)}}),b.addEventListener("error",S=>{console.error("SSE connection error:",S)}),()=>{w&&clearTimeout(w),b.close()}},[]),c(ce,{children:[c("div",{className:`min-h-screen ${x?"":"grid"} bg-cygray-10`,style:x?void 0:{gridTemplateColumns:"65px minmax(900px, 1fr)"},children:[!x&&n(_l,{labs:u}),c("div",{className:"max-h-screen overflow-auto bg-cygray-10",children:[d&&n(pd,{serverVersion:h}),a.length===0&&n(md,{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(yi,{})]})]}),n(jl,{toasts:m,onClose:p}),!v&&n(Il,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const Ld=$e(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(mi,{}),n(pi,{})]}),c("body",{children:[n(Ml,{children:n(kl,{children:n(Dd,{})})}),n(fi,{}),n(gi,{})]})]})}),Fd=Object.freeze(Object.defineProperty({__proto__:null,default:Ld,links:$d,loader:Rd},Symbol.toStringTag,{value:"Module"}));function qa(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function dn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=Ae(),[l,d]=_(null),[h,u]=_(!1),[m,p]=_(!1),[f,g]=_(!1),y=ve(!1),x=ve(null),v=ve(null),[b,w]=_(0),[C,N]=_(0),S=ve(null),k=ve(!1),{interactiveUrl:M,resetLogs:j}=ft(a,s),R=ve(t),O=ve(o);ne(()=>{O.current!==o&&(O.current=o,l&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),w(0),N(A=>A+1),k.current=!1,S.current&&(clearTimeout(S.current),S.current=null)))},[o,l]),ne(()=>{if(R.current!==t&&(R.current=t,x.current&&v.current&&r)){const A=qa(v.current),T=qa(r),F=x.current.replace(A,T);d(F),p(!0),g(!1),w(0),N(q=>q+1),k.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r]),ne(()=>{if(M){const A=M+"?width=600px";x.current=A,r&&(v.current=r),d(A),u(!1),p(!0)}},[M]),ne(()=>{const A=T=>{T.data.type==="codeyam-resize"&&(k.current||(k.current=!0,S.current&&(clearTimeout(S.current),S.current=null),w(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]);const P=()=>{k.current=!1,S.current&&clearTimeout(S.current);const A=500*Math.pow(2,b);S.current=setTimeout(()=>{k.current||(b<2?(w(T=>T+1),N(T=>T+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},A)};return ne(()=>{s&&!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(T){console.error("[useInteractiveMode] Failed to clear log file:",T)}j(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,j,a]),ne(()=>{const A=e,T=()=>{if(y.current&&A){const q=new URLSearchParams({action:"stop",analysisId:A});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const J=navigator.sendBeacon("/api/interactive-mode",q);console.log("[useInteractiveMode] sendBeacon result:",J),J||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:q,keepalive:!0}).catch(D=>console.error("Failed to stop interactive mode:",D)))}},F=()=>{T()};return window.addEventListener("beforeunload",F),()=>{window.removeEventListener("beforeunload",F),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:A}),T()}},[e]),{interactiveServerUrl:l,isStarting:h,isLoading:m,showIframe:f,iframeKey:C,onIframeLoad:P}}const gn=10,Od=1024;function yo({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1,lightMode:i=!1}){const[l,d]=_(null),h=ve(null),u=ae(()=>[...a].sort((b,w)=>b.width-w.width),[a]),{fittingPresets:m,overflowPresets:p}=ae(()=>{const b=[],w=[];for(const C of u)C.width<=Od?b.push(C):w.push(C);return w.sort((C,N)=>N.width-C.width),{fittingPresets:b,overflowPresets:w}},[u]),f=oe(b=>{if(!h.current)return null;const w=h.current.getBoundingClientRect(),C=b-w.left,N=w.width,S=N/2,M=(m.length>0?m[m.length-1].width:0)/2,j=S-M,R=S+M,O=p.length>0?(p.length-1)*gn:0;if(p.length>0){if(C<j){if(C<=O){const A=Math.min(Math.floor(C/gn),p.length-1);return p[A]}return p[p.length-1]}if(C>R){const A=N-C;if(A<=O){const T=Math.min(Math.floor(A/gn),p.length-1);return p[T]}return p[p.length-1]}}const P=Math.abs(C-S);for(let A=m.length-1;A>=0;A--){const T=m[A],F=m[A-1],q=T.width/2,J=F?F.width/2:0;if(P<=q&&P>=J)return T}return m[0]||p[p.length-1]||null},[m,p]),g=oe(b=>{const w=f(b.clientX);d(w),s==null||s(w)},[f,s]),y=oe(()=>{d(null),s==null||s(null)},[s]),x=oe(b=>{const w=f(b.clientX);w&&r(w)},[f,r]),v=l||{name:t,width:e};return c("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:g,onMouseLeave:y,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map(b=>{const w=b.width===e,C=(l==null?void 0:l.name)===b.name,N=b.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${N}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% + ${N}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)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((b,w)=>{const C=w*gn,N=b.width===e,S=(l==null?void 0:l.name)===b.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 ${N||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 ${N||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children: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:[v.name," - ",v.width,"px"]})})]})}function xo({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=_(""),[i,l]=_(""),d=()=>{const u=s.trim();if(!u){l("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors 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:s,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&s.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!s.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function bo(e){const[t,r]=_([]),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 s=oe(l=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=oe((l,d,h)=>{r(u=>{const m=u.findIndex(g=>g.name===l),p={name:l,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],s(f),f})},[s]),i=oe(l=>{r(d=>{const h=d.filter(u=>u.name!==l);return s(h),h})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Ln(){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 Ka=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],Yd=80;function Fn(){const[e,t]=_(0);return ne(()=>{const r=setInterval(()=>{t(a=>(a+1)%Ka.length)},Yd);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:Ka[e]})}async function zd({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw H("Invalid parameters",{status:400});const a=await jt(t);if(!a)throw H("Entity not found",{status:404});const s=await Vr(a),o=((l=s==null?void 0:s.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw H("Scenario not found",{status:404});const i=await De();return H({entity:a,scenario:o,analysis:s,projectSlug:i})}const br=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Bd=$e(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Ye(),o=It(),[i]=tn(),[l,d]=_(null),[h,u]=_(1440),[m,p]=_({name:"Desktop",width:1440,height:900}),[f,g]=_(!1),[y,x]=_(null),{customSizes:v,addCustomSize:b}=bo(s),w=ae(()=>[...br,...v],[v]),{interactiveServerUrl:C,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j}=dn({analysisId:a==null?void 0:a.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:s,enabled:!0}),{lastLine:R}=ft(s,N||S),O=()=>{o(`/entity/${t.sha}`)},P=(W,$)=>{u(W);const K=w.find(z=>z.width===W&&z.height===$);d(K||null),p({name:(K==null?void 0:K.name)||"Custom",width:W,height:$})},A=W=>{d(W),u(W.width),p({name:W.name,width:W.width,height:W.height})},T=W=>{b(W,m.width,m.height??900),g(!1),p($=>({...$,name:W}))},F=((a==null?void 0:a.scenarios)||[]).filter(W=>{var $;return!(($=W.metadata)!=null&&$.sameAsDefault)}),q=F.findIndex(W=>W.id===(r==null?void 0:r.id)),J=q+1,D=F.length,Y=q>0,L=q<F.length-1,I=()=>{if(Y){const W=F[q-1],$=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${$}`)}},E=()=>{if(L){const W=F[q+1],$=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${$}`)}},U=N||S||!k;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:Rs,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:I,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[J,"/",D]}),n("button",{onClick:E,disabled:!L,className:`${L?"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:O,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:`${br[br.length-1].width}px`,width:"100%"},children:n(yo,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:A,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)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:m.name,onChange:W=>{const $=w.find(K=>K.name===W.target.value);$&&A($)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[w.map(W=>n("option",{value:W.name,children:W.name},W.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:W=>{const $=parseInt(W.target.value,10);!isNaN($)&&$>0&&P($,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{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:`${m.width}px`,maxHeight:`${m.height}px`},children:[U&&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(Ln,{})}),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"}),R&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Fn,{}),R]})]})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:j,style:{opacity:k?1:0}},M)]}):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(Ln,{})}),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"}),R&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Fn,{}),R]})]})]})}),f&&n(xo,{width:m.width,height:m.height??900,onSave:T,onCancel:()=>g(!1)})]})}),Ud=Object.freeze(Object.defineProperty({__proto__:null,default:Bd,loader:zd},Symbol.toStringTag,{value:"Module"})),vo=Dr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Zr=()=>{const e=Bn(vo);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Xn=({children:e})=>{const[t,r]=_({height:720,width:1200}),[a,s]=_(1),[o,i]=_(1200),l=ve(null),d=oe(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),h=oe(m=>{s(m)},[]),u=oe(m=>{i(m)},[]);return n(vo.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},Wd=typeof window<"u";function Hd(){const[e,t]=_(null);return ne(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Jd=1200,Vd=720,Qa=30,Gd=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const h=Hd(),[u,m]=_(!1),[p,f]=_(!1),[g,y]=_(Jd),[x,v]=_(Vd),[b,w]=_(null),[C,N]=_(null),{dimensions:S,updateDimensions:k,iframeRef:M,updateScale:j,updateMaxWidth:R}=Zr(),O=ae(()=>Math.min(1,g/S.width),[g,S.width]),P=C!==null?C:O;ne(()=>{u||(j(P),l==null||l(P))},[P,j,l,u]),ne(()=>{R(g)},[g,R]);const A=oe(()=>{m(!0),N(O)},[O]),T=oe(()=>{m(!1),N(null)},[]),F=oe((L,I)=>{const E=C!==null?C:1,U=Math.round(I.size.width/E);k({width:U}),d==null||d(U,S.height)},[k,C,d,S.height]),q=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ne(()=>{const L=I=>{if(I.data.type==="codeyam-resize"){if(t&&I.data.name!==t||S.height===I.data.height||I.data.height===0)return;k({height:I.data.height})}};return window.addEventListener("message",L),()=>{window.removeEventListener("message",L)}},[M,t,a,S,k]),ne(()=>{p&&o&&o(M.current)},[p,o,M]),ne(()=>{if(!t)return;const L=setInterval(()=>{var I,E;(E=(I=M==null?void 0:M.current)==null?void 0:I.contentWindow)==null||E.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(L)},[t,M]),ne(()=>{const L=()=>{const I=document.getElementById("scenario-container");if(!I)return;const E=I.getBoundingClientRect(),U=I.clientWidth-Qa*2,W=window.innerHeight-E.top-Qa*2,$=Math.max(W,400),K=window.innerHeight-E.top;y(U),v($),w(K)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),ne(()=>{k({width:a,height:s})},[a,s,k]);const J=ae(()=>S.width*P,[S.width,P]),D=ae(()=>{const L=S.height,I=L*P;return L&&L!==720&&L!==900&&I<x?I:x},[S.height,x,P]),Y=oe(()=>{window.history.back()},[]);return!Wd||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
78
|
+
.react-resizable-handle-e {
|
|
79
|
+
display: flex !important;
|
|
80
|
+
align-items: center !important;
|
|
81
|
+
justify-content: center !important;
|
|
82
|
+
width: 6px !important;
|
|
83
|
+
height: 48px !important;
|
|
84
|
+
right: -8px !important;
|
|
85
|
+
top: 50% !important;
|
|
86
|
+
transform: translateY(-50%) !important;
|
|
87
|
+
cursor: ew-resize !important;
|
|
88
|
+
background: #d1d5db !important;
|
|
89
|
+
border-radius: 3px !important;
|
|
90
|
+
opacity: 0 !important;
|
|
91
|
+
transition: all 0.2s ease !important;
|
|
92
|
+
}
|
|
93
|
+
.react-resizable-handle-e:hover {
|
|
94
|
+
opacity: 0.8 !important;
|
|
95
|
+
background: #9ca3af !important;
|
|
96
|
+
}
|
|
97
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
98
|
+
opacity: 0.4 !important;
|
|
99
|
+
}
|
|
100
|
+
`}),n(h,{width:J,height:D,minConstraints:[300,200],maxConstraints:[g,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:A,onResizeStop:T,onResize:F,children:n("div",{className:"overflow-auto",style:{width:`${J}px`,height:`${D}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${P})`,transformOrigin:"top left"},children:r?n("iframe",{ref:M,className:"w-full h-full rounded-lg",src:r,onLoad:q,sandbox:"allow-scripts allow-same-origin"}):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:Y,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function qd({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[h,u]=_(!1),[m,p]=_(String(r)),[f,g]=_(String(a)),[y,x]=_(!1),[v,b]=_(!1),w=ve(null);ne(()=>{y||p(String(r))},[r,y]),ne(()=>{v||g(String(a))},[a,v]),ne(()=>{const P=A=>{w.current&&!w.current.contains(A.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const C=ae(()=>{const P=e.find(T=>T.width===r&&T.height===a);if(P)return P.name;const A=t.find(T=>T.width===r&&T.height===a);return A?A.name:"Custom"},[e,t,r,a]),N=C==="Custom",S=P=>{o(P.width,P.height),u(!1)},k=P=>{const A=P.target.value;p(A);const T=parseInt(A,10);!isNaN(T)&&T>0&&o(T,a)},M=P=>{const A=P.target.value;g(A);const T=parseInt(A,10);!isNaN(T)&&T>0&&o(r,T)},j=()=>{x(!1);const P=parseInt(m,10);(isNaN(P)||P<=0)&&p(String(r))},R=()=>{b(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&g(String(a))},O=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(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:C}),n("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children: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,A)=>P.width-A.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:A=>{A.stopPropagation(),C===P.name&&e.length>0&&o(e[0].width,e[0].height),l(P.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},P.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:k,onFocus:()=>x(!0),onBlur:j,onKeyDown:O,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:M,onFocus:()=>b(!0),onBlur:R,onKeyDown:O,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),s!==void 0&&s<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),N&&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 vr(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 Mr(e){return e&&(typeof e=="object"||Array.isArray(e))}function Kd(e){return Array.isArray(e)?e.length:void 0}function Qd(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,s)=>s.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((s,o)=>{const i=Mr(t[s]),l=Mr(t[o]);return i&&!l?1:!i&&l?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function Zd({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 Xd({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=oe(()=>{s&&s(e)},[s,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var wo=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(wo||{});const eu=({name:e,value:t,options:r,onChange:a})=>{const s=oe(o=>{a({target:{name:e,value:o.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:s,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},tu=({name:e,value:t,onChange:r})=>{const a=oe(s=>{const o=s.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
101
|
+
bg-gray-300 checked:bg-blue-600
|
|
102
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
103
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
104
|
+
checked:after:translate-x-4`})})};function nu({dataType:e,path:t,value:r,onChange:a}){const s=ae(()=>t[t.length-1],[t]),o=ae(()=>t.join("-"),[t]),i=oe(d=>{a(t,d.target.value)},[a,t]),l=oe(d=>{a(t,d.target.value)},[a,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(eu,{name:o,value:r,options:e.split("|"),onChange:i}):e===wo.BOOLEAN?n(tu,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function ru({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=_(!1),[l,d]=_(""),h=oe(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(x=>x.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Vn),f=await s(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(x,v)=>{const b=Object.assign({},x);return y(x)&&y(v)&&Object.keys(v).forEach(w=>{y(v[w])?w in x?b[w]=g(x[w],v[w]):Object.assign(b,{[w]:v[w]}):Object.assign(b,{[w]:v[w]})}),b},y=x=>x&&typeof x=="object"&&!Array.isArray(x);m.metadata.data=g(g((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),a(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,l,r,t,a,s]),u=oe(m=>{d(m.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?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 au({namedPath:e,path:t,last:r,onClick:a}){const s=oe(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:s,children:e[e.length-1]})}function su({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),a=ae(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>c("div",{className:"flex items-center gap-1",children:[n(au,{namedPath:e.namedPath.slice(0,o+a+1),path:e.path.slice(0,o+a+1),last:o+a===e.namedPath.length-1,onClick:t}),o+a<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${s}-${o+a}`))]})}function Za({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=ae(()=>r.data,[r]),h=ae(()=>Qd(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(su,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(ru,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(Mr(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(Xd,{path:y,namedPath:x,isArray:Array.isArray(d),count:Kd(d[u]),onClick:a},`data-${u}-${m}`)}if(u==="id")return null;const p=[...r.path,u];return n(nu,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:s},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==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 Xa({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=_(r),l=[];return a&&l.push("border-t"),s&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const ou=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:h})=>{const u=oe((k,M)=>{const j=Object.assign({},k),R=O=>O&&typeof O=="object"&&!Array.isArray(O);return R(k)&&R(M)&&Object.keys(M).forEach(O=>{R(M[O])?O in k?j[O]=u(k[O],M[O]):Object.assign(j,{[O]:M[O]}):Object.assign(j,{[O]:M[O]})}),j},[]),[m,p]=_({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=_(null),y=ae(()=>({...m.data}),[m]),x=ae(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),v=ae(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((M,j)=>{if(j.includes(".")){const[R,O]=j.split(".");M[R]||(M[R]={}),M[R][O]=k[j]}else M[j]=k[j];return M},{})},[r]),b=oe(async k=>{k.preventDefault();const M=k.target.querySelector('input[name="recapture"]'),j=(M==null?void 0:M.value)==="true",R={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:j,dataToSave:R,rawFormData:m.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(R,null,2).substring(0,1e3));const O=a==null?void 0:a.scenarios.map(P=>!s&&P.name===e.name?{...P,name:m.name,description:m.description,metadata:{...P.metadata,data:R}}:P);s&&O.push({name:m.name,description:m.description,metadata:{data:R,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",O),o&&await o(O,{recapture:j}),i&&i(m.name)},[a,e.name,m,y,s,o,i]),w=oe(k=>{p(M=>({...M,[k.target.name]:k.target.value}))},[]),C=oe(k=>{g(M=>{if(!M)return null;for(const j of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let R=j;for(const O of M.path)if(R=vr(R,O),!R)break;R&&(M.data=R)}return{...M}}),p({name:k.name,description:k.description,data:k.metadata.data})},[]),N=oe((k,M)=>{p(j=>{for(const R of[{"Function Arguments":j.data.argumentsData},{"Retrieved Data":j.data.mockData}]){let O=R;for(const P of k.slice(0,-1))if(O=vr(O,P),!O)break;if(O){const P=O[k[k.length-1]];g(A=>A?(A.namedPath[A.namedPath.length-1]===P&&(A.namedPath[A.namedPath.length-1]=M.toString()),A.data[k[k.length-1]]=M,{...A}):null),O[k[k.length-1]]=M}}return{...j}})},[]),S=oe(k=>{var O,P,A;if(k.length===0){g(null);return}let M=x;const j=[];let R=v;for(const T of k){if(j.push(isNaN(parseInt(T))?T:((O=M[T])==null?void 0:O.name)??((P=M[T])==null?void 0:P.title)??((A=M[T])==null?void 0:A.id)??T),M=vr(M,T),!M){console.log("Data not found",M,T),g(null);return}Array.isArray(R)?R=R[0]:R=R[T]}g({path:k,namedPath:j,data:M,structure:R})},[x,v]);return ne(()=>{const k=M=>{var j;M.data.type==="codeyam-log"&&((j=M.data.data)!=null&&j.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",M.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),ne(()=>{var k;if((k=l==null?void 0:l.current)!=null&&k.contentWindow){const M={arguments:y.argumentsData??[],...y.mockData??{}},j={type:"codeyam-override-data",name:e.name,data:JSON.stringify(M)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:j.type,name:j.name,dataPreview:JSON.stringify(M).substring(0,200)+"...",fullData:M}),l.current.contentWindow.postMessage(j,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:k=>void b(k),children:f?n(Za,{analysis:a,scenarioName:m.name,dataItem:f,onClick:S,onChange:N,onAIResult:C,onGenerateData:d,saveFeedback:h}):c(ce,{children:[n(Xa,{title:"Edit Name and Description",borderT:!0,children:n(Zd,{scenarioFormData:m,handleInputChange:w})}),e.metadata.data&&n(Xa,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Za,{analysis:a,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:S,onChange:N,onAIResult:C,onGenerateData:d,saveFeedback:h})})]})})};function er({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=ft(u??null,a||s);return r?c("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Gd,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:h},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Ln,{})}),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(Fn,{}),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(Ln,{})}),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(Fn,{}),g]})]})]})})}const iu=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function lu({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await qn(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(d=s.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(h=s.scenarios)==null?void 0:h.find(u=>u.name===Vn),l=await De();return H({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function cu(){var T,F,q;const e=Ye(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=It(),{iframeRef:l}=Zr(),[d,h]=_(!1),[u,m]=_(null),[p,f]=_(null),[g,y]=_(!1),[x,v]=_(!1),[b,w]=_(null),{interactiveServerUrl:C,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j}=dn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),R=oe(async(J,D)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",D),console.log("[EditScenario] Scenarios to save:",J);try{const Y={analysis:t,scenarios:J};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:J.length,scenarioNames:J.map(E=>E.name)});const L=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}),I=await L.json();if(console.log("[EditScenario] API response:",I),!L.ok||!I.success)throw new Error(I.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),D!=null&&D.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}),m("Changes saved. Capturing screenshot...");const E={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",E);const U=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});console.log("[EditScenario] Capture response status:",U.status);const W=await U.json();if(console.log("[EditScenario] Capture response body:",W),!U.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 =========="),m("Recapture successful")}else if(D!=null&&D.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const E=new FormData;E.append("analysisId",t.id||""),E.append("scenarioId",r.id||"");const U=await fetch("/api/recapture-scenario",{method:"POST",body:E}),W=await U.json();if(!U.ok||!W.success)throw new Error(W.error||"Failed to trigger recapture");console.log("Recapture queued:",W),f(W.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(Y){console.error("Error saving scenarios:",Y),m(`Error: ${Y instanceof Error?Y.message:String(Y)}`)}finally{h(!1)}},[t,r.id,C]),O=oe(J=>{},[]),P=oe(async(J,D)=>{var I;const Y=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:J,existingScenarios:t.scenarios,scenariosDataStructure:(I=t.metadata)==null?void 0:I.scenariosDataStructure,editingMockName:r.name,editingMockData:D==null?void 0:D.data})}),L=await Y.json();if(!Y.ok||!L.success)throw new Error(L.error||"Failed to generate scenario data");return L.data},[t,r.name]),A=oe(async()=>{var J;if(!r.id){w("Cannot delete scenario without ID");return}y(!0),w(null);try{const D=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((J=r.metadata)==null?void 0:J.screenshotPaths)||[]})}),Y=await D.json();if(!D.ok||!Y.success)throw new Error(Y.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(D){console.error("[EditScenario] Error deleting scenario:",D),w(D instanceof Error?D.message:"Failed to delete scenario"),v(!1)}finally{y(!1)}},[r.id,(T=r.metadata)==null?void 0:T.screenshotPaths,s,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(se,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(F=t.entity)==null?void 0:F.name]})}),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(ou,{currentScenario:r,defaultScenario:a,dataStructure:((q=t.metadata)==null?void 0:q.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:R,onNavigate:O,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(se,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),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 A(),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:()=>v(!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:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(er,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const du=$e(function(){return n(Xn,{children:n(cu,{})})}),uu=Object.freeze(Object.defineProperty({__proto__:null,default:du,loader:lu,meta:iu},Symbol.toStringTag,{value:"Module"}));function hu({executionFlows:e,selections:t,onChange:r,disabled:a=!1}){const s=oe(i=>t.some(l=>l.flowId===i),[t]),o=oe(i=>{s(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,s]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=s(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:()=>o(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((h,u)=>c("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",n("span",{className:"text-gray-400",children:h.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function Xr(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;r.forEach(d=>{a.set(d.id,d)});const s=[];t.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(m=>{const p=a.get(m);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),s.push({scenario:d,coveredFlowIds:h})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:s}}function mu(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const pu=({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 fu({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await qn(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=(i=a.scenarios)==null?void 0:i.find(l=>l.name===Vn);if(!s)throw new Response("Default scenario not found",{status:404});const o=await De();return H({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function gu(){var Y;const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Ye(),o=It(),{iframeRef:i}=Zr(),[l,d]=_(""),[h,u]=_(400),[m,p]=_(!1),[f,g]=_(!1),[y,x]=_(!1),[v,b]=_(null),[w,C]=_(null),[N,S]=_([]),k=ae(()=>{var I;return!((I=e==null?void 0:e.metadata)!=null&&I.executionFlows)||!(e!=null&&e.scenarios)?[]:Xr(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:M,isStarting:j,isLoading:R,showIframe:O,iframeKey:P,onIframeLoad:A}=dn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:s,enabled:!0}),T=oe(async()=>{var L,I,E,U;if(!l.trim()&&N.length===0){b("Please describe how you want to change the scenario or select execution flows");return}g(!0),b(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:(L=e.metadata)==null?void 0:L.scenariosDataStructure,flowSelections:N.length>0?N:void 0})}),$=await W.json();if(!W.ok||!$.success)throw new Error($.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",$.data);const K=$.data;if(!K.name||!K.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),x(!0);const G={name:K.name,description:K.description||l,metadata:{data:K.data,interactiveExamplePath:(I=t.metadata)==null?void 0:I.interactiveExamplePath}},z=[...e.scenarios||[],G],B=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:z})}),Z=await B.json();if(!B.ok||!Z.success)throw new Error(Z.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",Z);const V=(U=(E=Z.analysis)==null?void 0:E.scenarios)==null?void 0:U.find(X=>X.name===K.name);if(!(V!=null&&V.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(M){C("Capturing screenshot...");const X=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:M,scenarioId:V.id,projectId:e.projectId,viewportWidth:1440})}),ue=await X.json();!X.ok||!ue.success?(console.error("[CreateScenario] Capture failed:",ue),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${V.id}`)},1e3)}catch(W){console.error("[CreateScenario] Error:",W),b(W instanceof Error?W.message:String(W)),C(null)}finally{g(!1),x(!1)}},[l,N,e,t,a,M,o]),F=f||y,q=oe(()=>{p(!0)},[]),J=oe(L=>{if(!m)return;const I=L.clientX;I>=250&&I<=600&&u(I)},[m]),D=oe(()=>{p(!1)},[]);return ne(()=>(m?(document.addEventListener("mousemove",J),document.addEventListener("mouseup",D)):(document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",D)),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",D)}),[m,J,D]),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 o(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),c("div",{className:"flex items-end gap-8 shrink-0",children:[n(se,{to:`/entity/${a}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children: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:((Y=e==null?void 0:e.scenarios)==null?void 0:Y.length)||0})]})}),n(se,{to:`/entity/${a}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(se,{to:`/entity/${a}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(se,{to:`/entity/${a}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(se,{to:`/entity/${a}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),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:`${h}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."})]}),k.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"," ",N.length>0&&c("span",{className:"text-blue-600",children:["(",N.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(hu,{executionFlows:k,selections:N,onChange:S,disabled:F})})]}),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:L=>d(L.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:F})]}),c("div",{className:"space-y-2",children:[n("button",{onClick:()=>void T(),disabled:F||!l.trim()&&N.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:F?"Creating...":"Create Scenario"}),w&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:w}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),c("div",{onMouseDown:q,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:m?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
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(er,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:M,isStarting:j,isLoading:R,showIframe:O,iframeKey:P,onIframeLoad:A,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const yu=$e(function(){return n(Xn,{children:n(gu,{})})}),xu=Object.freeze(Object.defineProperty({__proto__:null,default:yu,loader:fu,meta:pu},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 Co(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 No=Co(process.env.DEFAULT_SMALLER_MODEL,ie.Model.OPENAI_GPT4_1_MINI),bu=Co(process.env.DEFAULT_LARGER_MODEL,ie.Model.OPENAI_GPT4_1),Qe={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},wr={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},vu={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Cr={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},lt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},wu={[ie.Model.OPENAI_GPT5_1]:{id:ie.Model.OPENAI_GPT5_1,provider:Qe,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ie.Model.OPENAI_GPT5]:{id:ie.Model.OPENAI_GPT5,provider:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:wr,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:wr,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:wr,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:vu,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:lt,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:lt,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:lt,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:lt,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:lt,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:Cr,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:Cr,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:Cr,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ie.Model.PHIND_CODELLAMA]:{id:ie.Model.PHIND_CODELLAMA,provider:Qe,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.GOOGLE_GEMINI_PRO]:{id:ie.Model.GOOGLE_GEMINI_PRO,provider:lt,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:lt,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:lt,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:Qe,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function tr(e){const t=wu[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Cu(e){return tr(e).maxCompletionTokens}function Nu(e){return tr(e).pricing}const es=1e6;function Su({model:e,usage:t}){const r=Nu(e);return r?t.prompt_tokens*(r.input/es)+t.completion_tokens*(r.output/es):null}function Eu({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const a=t.usage||{prompt_tokens:0,completion_tokens:0},s=Su({model:r,usage:a});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:s?Math.round(s*1e5)/1e5:void 0}}function Au({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??No,i=tr(o);Cu(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:a==="json_schema"&&s?{type:"json_schema",json_schema:{name:s.name,schema:s.schema,strict:s.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Tr="/tmp/codeyam-e2e-tracking";let Nr,Sr;function ku(){return Nr===void 0&&(Nr=process.env.CODEYAM_E2E_TRACK_DATA==="true"),Nr}function Pu(){return Sr===void 0&&(Sr=!process.env.CODEYAM_LLM_FIXTURES_DIR),Sr}function _u(){Q.existsSync(Tr)||Q.mkdirSync(Tr,{recursive:!0})}function Mu(e){const t=JSON.stringify(e,null,0);return sl.createHash("md5").update(t).digest("hex")}function Tu(e,t,r){return[e].join("_")+".json"}function So(e,t,r,a){if(!ku())return;_u();const s=Tu(e),o=ee.join(Tr,s),i=Mu(t);if(Pu()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:a,dataHash:i,data:t};Q.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(Q.existsSync(o)){const l=JSON.parse(Q.readFileSync(o,"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=jr(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const h=o.replace(".json","_DIFF.json");Q.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:r,scenarioName:a,firstRun:l.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function jr(e,t,r=""){const a=[];if(typeof e!=typeof t)return a.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),a;if(e===null||t===null)return e!==t&&a.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),a;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&a.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const s=Math.max(e.length,t.length);for(let o=0;o<s;o++)a.push(...jr(e[o],t[o],`${r}[${o}]`));return a}if(typeof e=="object"&&typeof t=="object"){const s=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...s,...o]));for(const l of i){const d=e[l],h=t[l];l in e?l in t?a.push(...jr(d,h,`${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 s=JSON.stringify(e),o=JSON.stringify(t);s.length<100&&o.length<100?a.push(`${r||"root"}: ${s} vs ${o}`):a.push(`${r||"root"}: values differ (${s.length} chars vs ${o.length} chars)`)}return a}Yr(Or);const yn=new ul({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),ts={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},ct={};async function Ir({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=No,attempts:i=0}){var S,k,M,j,R,O,P;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ju(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${yn.size}, running=${yn.pending}]`);const l=Date.now();let d,h=0;const u=tr(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new dl({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},g=Au(f),y=await yn.add(()=>(d=Date.now(),za(async()=>{const A=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],F=setInterval(()=>{const q=Math.floor((Date.now()-A)/1e3),J=Math.floor(q/10)%T.length;Ua(1,`${T[J]} [type=${e}, model=${o}, elapsed=${q}s]`)},1e4);try{return await p.chat.completions.create(g,{timeout:300*1e3})}finally{clearInterval(F)}},{...ts,onFailedAttempt:A=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:A,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})),{throwOnTimeout:!0}),x=Date.now(),v=Eu({chatRequest:f,chatCompletion:y,model:o});if(!v)throw new Error("Failed to get LLM call stats");v.retries=h,v.wait_ms=d-l,v.duration_ms=x-l;const b=(S=y.choices)==null?void 0:S[0];let w=null;if(b){if(!b.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=(k=b.message)==null?void 0:k.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const N=a?C&&(((M=C.match(/\{[\s\S]*\}/))==null?void 0:M[0])??C):C;if(!N){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:N,rawCompletion:w,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Ir({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(N.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(N)}catch(A){if(console.log("CodeYam Error: Invalid JSON in completion",{error:A.message,model:o,completion:N.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:A.message});const T=`Your previous response contained invalid JSON with the following error:
|
|
110
|
+
|
|
111
|
+
${A.message}
|
|
112
|
+
|
|
113
|
+
Here was your previous response:
|
|
114
|
+
\`\`\`
|
|
115
|
+
${N}
|
|
116
|
+
\`\`\`
|
|
117
|
+
|
|
118
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,F=await yn.add(()=>za(async()=>{const Y=Date.now(),L=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],I=setInterval(()=>{const E=Math.floor((Date.now()-Y)/1e3),U=Math.floor(E/10)%L.length;Ua(1,`${L[U]} [type=${e}, model=${o}, elapsed=${E}s]`)},1e4);try{return await p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:N},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval(I)}},{...ts,onFailedAttempt:Y=>{console.log("CodeYam Error: Correction call failed",{error:Y,attempts:i})}}),{throwOnTimeout:!0}),q=(O=(R=(j=F.choices)==null?void 0:j[0])==null?void 0:R.message)==null?void 0:O.content;let J=q;q&&(J=q.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const D=J&&(((P=J.match(/\{[\s\S]*\}/))==null?void 0:P[0])??J);if(!D)throw new Error("Correction attempt returned empty completion");try{JSON.parse(D),console.log("CodeYam: JSON correction successful");const Y=Date.now();return v.duration_ms=Y-l,{finishReason:F.choices[0].finish_reason,completion:D,stats:v}}catch(Y){return console.log("CodeYam Error: Corrected JSON still invalid",{error:Y.message,correctedCompletion:D.substring(0,500)}),await Ir({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${A.message}`)}return So(`completionCall_${e}`,{completion:N,finishReason:y.choices[0].finish_reason}),{finishReason:y.choices[0].finish_reason,completion:N,stats:v}}async function ju(e,t,r){var o,i,l,d,h;const a=await import("fs"),s=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!a.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=a.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const m={};for(const b of u)try{const w=a.readFileSync(s.join(t,b),"utf-8"),C=JSON.parse(w);m[C.prompt_type]||(m[C.prompt_type]=[]),m[C.prompt_type].push(C)}catch(w){console.warn(`Failed to parse LLM fixture file ${b}:`,w)}for(const b of Object.keys(m))m[b].sort((w,C)=>{const N=w.created_at??0,S=C.created_at??0;return N-S});const p=m[e];if(!p||p.length===0){const b=Object.keys(m).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),w=b==null?void 0:b[1];if(w){const C={};for(const S of p)try{const M=((o=JSON.parse(S.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";C[M]||(C[M]=[]),C[M].push(S)}catch{}const N=C[w];if(N&&N.length>0){const S=`${t}::${e}::${w}`;ct[S]===void 0&&(ct[S]=0);const k=ct[S];ct[S]=(k+1)%N.length,f=N[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${w}' [${k+1}/${N.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 b=`${t}::${e}`;ct[b]===void 0&&(ct[b]=0);const w=ct[b];ct[b]=(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 v=x&&(((h=x.match(/\{[\s\S]*\}/))==null?void 0:h[0])??x);return So(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function ns(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Iu(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=an(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let l;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?l=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:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=ns();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new Jn().send(new hl({TableName:ns(),Item:pl(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Jn({});new Jn({});new Jn({});const $u=3,Ru=2,ea=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+$u*String(t).length*(1+Ru)});new zr(ea());new zr(ea());new zr(ea());class Du{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 Lu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Fu{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ou{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Yu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class zu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];if(a.addType(o,"function"),a.addEquivalence(o.withParameter(1),r.withElement("*")),s.args.length>1){const i=s.args[1];a.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class Bu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Uu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.withReturnValues();a.addType(s,"unknown")}isComplete(){return!0}}class Wu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>2)for(let o=2;o<s.args.length;o++){const i=s.args[o];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Hu{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0)for(let o=0;o<s.args.length;o++)a.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class Ju{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Vu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Gu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class qu{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Ku{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Qu{getReturnType(){return"object"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"array")}}isComplete(){return!0}}class Zu{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 Xu{getReturnType(){return"unknown"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class eh{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class th{getReturnType(){return"array"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function nh(){const e=new Du;return e.register("filter",new Lu,"Array"),e.register("map",new Vu,"Array"),e.register("flatMap",new Gu,"Array"),e.register("join",new Ju,"Array"),e.register("find",new Yu,"Array"),e.register("findLast",new Ku,"Array"),e.register("at",new qu,"Array"),e.register("reduce",new zu,"Array"),e.register("concat",new Bu,"Array"),e.register("slice",new Uu,"Array"),e.register("splice",new Wu,"Array"),e.register("push",new Hu,"Array"),e.register("some",new Fu,"Array"),e.register("every",new Ou,"Array"),e.register("fromEntries",new Qu,"Object"),e.register("split",new Zu,"String"),e.register("then",new Xu,"Promise"),e.register("useState",new th,"React"),e.register("useMemo",new eh,"React"),e}nh();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const rh=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),ah=new Set(["find","findLast","at","pop","shift"]),sh=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),oh=new Set([...rh,...ah,...sh]),ih=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),lh=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),ch=new Set([...ih,...lh]);[...oh,...ch];class dh{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const s=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${o}${s}${r}`,JSON.stringify(a)):console.info(`${o}${s}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new dh({enabled:!1});function vt(e,t){const r={added:{},removed:{},changed:{}},a=new Set(Object.keys(e??{})),s=new Set(Object.keys(t??{}));for(const o of s)a.has(o)||(r.added[o]=t[o]);for(const o of a)s.has(o)||(r.removed[o]=e[o]);for(const o of a)s.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function uh(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function xn(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let hh=0;class ta{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++hh,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,a){var d,h,u,m;if(!this.isEnabled())return;const s=this.traces.get(t);if(!s)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,a);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(a)),i={stage:r,timestamp:Date.now(),data:o},l=s.stages[s.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:vt(l.data.signatureSchema,o.signatureSchema),returnValueSchema:vt(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of p){const g=(d=l.data.dependencySchemas)==null?void 0:d[f],y=(h=o.dependencySchemas)==null?void 0:h[f];for(const x of new Set([...Object.keys(g??{}),...Object.keys(y??{})])){const v=`${f}::${x}`,b=(u=g==null?void 0:g[x])==null?void 0:u.returnValueSchema,w=(m=y==null?void 0:y[x])==null?void 0:m.returnValueSchema,C=vt(b,w);uh(C)&&(i.diffFromPrevious.dependencySchemas[v]=C)}}}s.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const a=this.traces.get(t);a&&a.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}flush(){var d;if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(h=>`${h}(${this.traces.get(h).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const a={},s=new Map;for(const[h,u]of this.traces){let m=0;for(const p of u.stages){if(!p.diffFromPrevious)continue;const g=`${((d=u.stages[u.stages.indexOf(p)-1])==null?void 0:d.stage)??"start"}→${p.stage}`;if(a[g]||(a[g]={added:0,removed:0,changed:0}),p.diffFromPrevious.signatureSchema){const y=p.diffFromPrevious.signatureSchema;a[g].added+=Object.keys(y.added).length,a[g].removed+=Object.keys(y.removed).length,a[g].changed+=Object.keys(y.changed).length,m+=xn(y)}if(p.diffFromPrevious.returnValueSchema){const y=p.diffFromPrevious.returnValueSchema;a[g].added+=Object.keys(y.added).length,a[g].removed+=Object.keys(y.removed).length,a[g].changed+=Object.keys(y.changed).length,m+=xn(y)}}s.set(h,m)}const o=[...s.entries()].sort((h,u)=>u[1]-h[1]).slice(0,10).map(([h])=>h),i={meta:{timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},summary:{stageChangeCounts:a,entitiesWithMostChanges:o},entities:Object.fromEntries(this.traces)},l=ee.dirname(this.outputPath);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0}),Q.writeFileSync(this.outputPath,JSON.stringify(i,null,2)),this.log(`flush: wrote trace to ${this.outputPath}`)}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=Q.readFileSync(t,"utf-8"),a=JSON.parse(r),s=new ta({enabled:!1});s.projectSlug=a.meta.projectSlug;for(const[o,i]of Object.entries(a.entities))s.traces.set(o,i);return s}getSummary(){var s,o,i;const t={},r=new Map;for(const[l,d]of this.traces){let h=0;for(let u=1;u<d.stages.length;u++){const m=d.stages[u],f=`${((s=d.stages[u-1])==null?void 0:s.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=m.diffFromPrevious)!=null&&o.signatureSchema){const g=m.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,h+=xn(g)}if((i=m.diffFromPrevious)!=null&&i.returnValueSchema){const g=m.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,h+=xn(g)}}r.set(l,h)}const a=[...r.entries()].sort((l,d)=>d[1]-l[1]).slice(0,10).map(([l,d])=>({name:l,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:a}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(a=>({stage:a.stage,diffFromPrevious:a.diffFromPrevious?{signatureSchema:a.diffFromPrevious.signatureSchema,returnValueSchema:a.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const a=this.traces.get(t);return a?r?a.operations.filter(s=>s.path&&r.test(s.path)):a.operations:[]}tracePath(t,r){var o,i;const a=this.traces.get(t),s=[];if(!a)return{entityName:t,path:r,history:s};for(const l of a.stages){const d=(o=l.data.signatureSchema)==null?void 0:o[r],h=(i=l.data.returnValueSchema)==null?void 0:i[r],u=d??h;u!==void 0&&s.push({stage:l.stage,value:u})}for(const l of a.operations)l.path===r&&s.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:s}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const a=this.traces.get(t);if(!a)return[];const s=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of a.stages){for(const[l,d]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&s.push({stage:i.stage,path:l,type:d,schemaType:"signature"});for(const[l,d]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&s.push({stage:i.stage,path:l,type:d,schemaType:"returnValue"});for(const[l,d]of Object.entries(i.data.dependencySchemas??{}))for(const[h,u]of Object.entries(d))for(const[m,p]of Object.entries(u.returnValueSchema??{}))o.test(m)&&s.push({stage:i.stage,path:`${l}/${h}::${m}`,type:p,schemaType:"dependency"})}return s}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let a=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){a=r.stages[d];break}if(!a)return[];const s=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,h)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],p=u[2]==="[]";if(s.has(m))return;const f=m+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:h})};for(const[,d]of Object.entries(a.data.dependencySchemas??{}))for(const[,h]of Object.entries(d))for(const[u,m]of Object.entries(h.returnValueSchema??{}))i(u,m);const l=[];for(const[d,h]of o)new Set(h.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:d,paths:h.map(m=>({...m,stage:a.stage}))});return l.sort((d,h)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(h.paths.map(p=>p.type)).size-u}),l}getStageDiffSummary(t,r,a){const s=this.traces.get(t);if(!s)return null;const o=s.stages.find(p=>p.stage===r),i=s.stages.find(p=>p.stage===a);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},h=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),m=new Set(Object.keys(h));for(const p of m)u.has(p)?d[p]!==h[p]&&l.typeChanged.push({path:p,from:d[p],to:h[p]}):l.added.push(`${p}: ${h[p]}`);for(const p of u)m.has(p)||l.removed.push(`${p}: ${d[p]}`);return l}traceSchemaTransform(t,r,a,s,o){if(!this.enabled)return s(a),a;const i={...a};s(a);const l=vt(i,a);for(const[d,h]of Object.entries(l.added))this.operation(t,{operation:r,path:d,before:void 0,after:h,context:{...o,changeType:"added"}});for(const[d,h]of Object.entries(l.removed))this.operation(t,{operation:r,path:d,before:h,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:h,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:d,before:h,after:u,context:{...o,changeType:"changed"}});return a}traceSchemaTransformResult(t,r,a,s,o){if(!this.enabled)return;const i=vt(a,s);for(const[l,d]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[l,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:d,to:h}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:d,after:h,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,a,s,o="both"){if(!this.enabled){for(const i in a)for(const l in a[i]){const d=a[i][l];(o==="signature"||o==="both")&&d.signatureSchema&&s(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&s(d.returnValueSchema)}return}for(const i in a)for(const l in a[i]){const d=a[i][l],h={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,s,{...h,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,s,{...h,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,a,s){var i;if(!this.enabled){s();return}const o={};for(const l in a){o[l]={};for(const d in a[l]){const h=a[l][d];o[l][d]={sig:{...h.signatureSchema||{}},rv:{...h.returnValueSchema||{}}}}}s();for(const l in a)for(const d in a[l]){const h=a[l][d],u=(i=o[l])==null?void 0:i[d],m={filePath:l,dependencyName:d};if(h.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=vt(p,h.signatureSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...m,schemaType:"signature",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...m,schemaType:"signature",changeType:"changed"}})}if(h.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=vt(p,h.returnValueSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...m,schemaType:"returnValue",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...m,schemaType:"returnValue",changeType:"changed"}})}}}}function mh(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const rs=new ta({enabled:mh(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{rs.isEnabled()&&rs.flush()});function Eo(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 ml.parse(e)}catch(r){const s=r.message.match(/invalid character .* at (\d+):(\d+)/);if(s){const o=parseInt(s[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),Eo(e)}return null}}function ph({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:a}){let s="";return a&&a.length>0&&(s=`
|
|
119
|
+
User-selected Execution Flow Values:
|
|
120
|
+
The user has specifically requested these values be used in the scenario:
|
|
121
|
+
${a.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
122
|
+
`)}
|
|
123
|
+
|
|
124
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
125
|
+
`),`Mock Scenario Data Structure:
|
|
126
|
+
\`\`\`
|
|
127
|
+
${JSON.stringify(r,null,2)}
|
|
128
|
+
\`\`\`
|
|
129
|
+
Existing Mock Scenario Data:
|
|
130
|
+
\`\`\`
|
|
131
|
+
${JSON.stringify(t,null,2)}
|
|
132
|
+
\`\`\`
|
|
133
|
+
${s}
|
|
134
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
135
|
+
`}function fh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===Vn);return`Mock Scenario Data Structure:
|
|
136
|
+
\`\`\`
|
|
137
|
+
${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
|
|
138
|
+
\`\`\`
|
|
139
|
+
|
|
140
|
+
Existing Mock Scenario Data:
|
|
141
|
+
\`\`\`
|
|
142
|
+
${JSON.stringify(a.map(i=>({name:i.name,data:Wt(o.metadata.data,i.metadata.data)})),null,2)}
|
|
143
|
+
\`\`\`
|
|
144
|
+
|
|
145
|
+
Mock Scenario that should be edited: "${t}"
|
|
146
|
+
${r?`The portion of the data that should be edited:
|
|
147
|
+
\`\`\`
|
|
148
|
+
${JSON.stringify(r,null,2)}
|
|
149
|
+
\`\`\``:""}
|
|
150
|
+
|
|
151
|
+
How this data should be changed: "${e}"
|
|
152
|
+
`}async function gh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,flowSelections:o,model:i}){const l=t?fh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):ph({description:e,existingScenarios:a,scenariosDataStructure:s,flowSelections:o}),d=await Ir({type:"guessScenarioDataFromDescription",systemMessage:t?xh(r):yh,prompt:l,model:i??bu});await Iu({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:h}=d;return h?Eo(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const yh=`
|
|
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
|
+
`,xh=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 bh({request:e}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return H({error:"Missing required field: description or flowSelections"},{status:400});const d=await gh({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:l}),h=(d==null?void 0:d.data)||d;return H({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),H({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const vh=Object.freeze(Object.defineProperty({__proto__:null,action:bh},Symbol.toStringTag,{value:"Module"}));async function wh(e,t){const r=pe();if(!r)return{entityCalls:[],analysisCalls:[]};const a=ee.join(r,".codeyam","llm-calls");try{await Ie.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const l=(await Ie.readdir(a)).filter(v=>v.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],m=[];for(const v of l)v.startsWith(d)||h&&v.startsWith(h)?u.push(v):m.push(v);const p=u.map(async v=>{try{const b=ee.join(a,v),w=await Ie.readFile(b,"utf-8");return JSON.parse(w)}catch{return null}}),f=m.map(async v=>{try{const b=ee.join(a,v),w=await Ie.readFile(b,"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(v=>v!==null);for(const v of x)v.object_id===e?s.push(v):t&&v.object_id===t&&o.push(v);s.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function Ch({params:e,request:t}){const{entitySha:r}=e;if(!r)return H({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await wh(r,s);return H(o)}const Nh=Object.freeze(Object.defineProperty({__proto__:null,loader:Ch},Symbol.toStringTag,{value:"Module"}));function Sh(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 Eh(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Eh(e){const t=e.trim().split(`
|
|
190
|
+
`).filter(a=>a.length>0),r=[];for(const a of t){const s=a[0],o=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),l,d=!1,h;if(s==="A"||o==="A")l="added",d=s==="A";else if(s==="M"||o==="M")l="modified",d=s==="M";else if(s==="D"||o==="D")l="deleted",d=s==="D";else if(s==="R"||o==="R"){l="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=le.join(u,i);try{const p=(g,y)=>{const x=Et.readdirSync(g,{withFileTypes:!0}),v=[];for(const b of x){const w=le.join(g,b.name),C=le.relative(u,w);b.isDirectory()?v.push(...p(w,y)):b.isFile()&&v.push(C)}return v},f=p(m,u);for(const g of f)r.push({path:g,status:l,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...h&&{oldPath:h}})}return r}function Ah(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 kh(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 Ph(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 Ao(){const e=pe();return e?Sh(e):[]}function _h(){const e=pe();return e?Ah(e):null}function Mh(){const e=pe();return e?kh(e):"main"}function Th(){const e=pe();return e?Ph(e):[]}function ko(e,t){const r=pe();return r?jh(e,t,r):[]}function jh(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 h=l[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=l[1],h=l[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function Ih(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=Et.readFileSync(le.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),s=""}return{oldContent:a,newContent:s,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function $h(e){const t=pe();return t?Ih(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Rh(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Me(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Nn(e,t,r){const a=pe();return a?Rh(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function as(e,t){var r,a;try{return((a=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:a.trim())??null}catch(s){return console.error(`Failed to get commit SHA for ${e}:`,s),""}}function Dh(e,t,r,a){const s=Un.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function Po(){const e=pe();if(!e)throw new Error("No project root found");const t=le.join(e,".codeyam","cache","branch-entity-diff");return Et.existsSync(t)||Et.mkdirSync(t,{recursive:!0}),t}function Lh(e){try{const t=Po(),r=le.join(t,`${e}.json`);if(!Et.existsSync(r))return null;const a=Et.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Fh(e,t){try{const r=Po(),a=le.join(r,`${e}.json`);Et.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Oh(e,t,r){const a=Tn(t,e),s=Tn(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),l=[],d=[],h=[];for(const[u,m]of i){const p=o.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):l.push(m)}for(const[u,m]of o)i.has(u)||h.push(m);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:h}}function Yh(e,t){const r=pe();if(!r)throw new Error("No project root found");const a=as(e,r),s=as(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Dh(e,t,a,s),i=Lh(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=ko(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=Nn(u.path,e,t),p=Tn(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=Nn(u.path,e,t),p=Tn(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=Nn(u.path,e,t),p=Oh(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Fh(o,h),h}function zh({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return H({error:"Missing required parameters: base and compare"},{status:400});const s=Yh(r,a);return H(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),H({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Bh=Object.freeze(Object.defineProperty({__proto__:null,loader:zh},Symbol.toStringTag,{value:"Module"}));async function Uh({request:e}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:s,viewportWidth:o=1440}=t;if(!r||!a||!s)return H({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=pe();if(!i)return H({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:s,projectRoot:i,viewportWidth:o}),h=await new Promise(p=>{const f=ee.join(i,".codeyam","db.sqlite3"),g=Wn("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",x="";g.stdout.on("data",v=>{const b=v.toString();y+=b;const w=b.trim().split(`
|
|
193
|
+
`);for(const C of w)C.includes("[Capture]")&&console.log(C)}),g.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),g.on("close",v=>{p(v===0?{success:!0,output:y}:{success:!1,output:y,error:x||`Process exited with code ${v}`})}),g.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),p({success:!1,output:"",error:v.message})})});if(!h.success)return H({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return H({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return H(m)}catch(t){return console.error("[Capture] Error:",t),H({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Wh=Object.freeze(Object.defineProperty({__proto__:null,action:Uh},Symbol.toStringTag,{value:"Module"}));async function Hh(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Re();const a=await st({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=Ce(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await Rt(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=pe();if(!d)throw new Error("Project root not found");const h=ee.join(d,".codeyam","config.json"),u=JSON.parse(Q.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Jh(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Re();const a=await st({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=(u=a.scenarios)==null?void 0:u.find(m=>m.id===t);if(!s)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${s.name}`),await Rt(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===s.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 ${s.name} for recapture`);const o=pe();if(!o)throw new Error("Project root not found");const i=ee.join(o,".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:h}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function Vh({request:e,context:t}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return H({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return H({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await Jh(s,o,r);return console.log("[API] Scenario recapture queued",i),H({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),H({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Gh=Object.freeze(Object.defineProperty({__proto__:null,action:Vh},Symbol.toStringTag,{value:"Module"})),qh=/<system-reminder>[\s\S]*?<\/system-reminder>/g,ss=2e3;function Kh(){return`/private/tmp/claude-501/-${(pe()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Qh="/tmp/claude-rule-markers";function Zh(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),a=String(t.path||"");return a?`"${r}" in ${a}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const Xh=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function em(e){const t=[],r=new Set;for(const a of e)if(!(a.type!=="tool_call"||!a.name||!a.input)){if(a.name==="Write"||a.name==="Edit"){const s=String(a.input.file_path||"");if(s.includes(".claude/rules/")){const o=s.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${a.name}:${o}`;r.has(i)||(r.add(i),a.name==="Write"?t.push({action:"created",filePath:o,content:String(a.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(a.input.old_string||""),newString:String(a.input.new_string||"")}))}}else if(a.name==="Bash"){const s=String(a.input.command||"");if(s.includes("codeyam memory touch")){const o=`touch:${s}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:s}))}}}return t}function tm(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const a of Xh)if(r.includes(a))return!0}return!1}function nm(e){const t=[],r={};for(const a of e){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,h=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:h,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,p=String(m.tool_use_id||"");let f=m.content;const g=!!m.is_error;typeof f=="string"&&(f=f.replace(qh,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:g,timestamp:h})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const p=String(m.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:h})}else if(m.type==="tool_use"){const p=String(m.id||""),f=String(m.name||"unknown"),g=m.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:g,timestamp:h})}}}return t}function rm(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}async function am({request:e}){var t;try{const a=((t=new URL(e.url).searchParams.get("search"))==null?void 0:t.toLowerCase())||"",s=Kh(),o=Qh,i=[];if(Mt(s)){const d=await Oa(s);for(const h of d)if(h.endsWith(".output")){const u=le.join(s,h),m=await Ya(u);i.push({filePath:u,stem:h.replace(".output",""),mtime:m.mtimeMs})}}if(Mt(o)){const d=await Oa(o);for(const h of d)if(h.endsWith(".log")){const u=le.join(o,h),m=await Ya(u);i.push({filePath:u,stem:h.replace(".log",""),mtime:m.mtimeMs})}}i.sort((d,h)=>h.mtime-d.mtime);const l=[];for(const d of i){const u=(await Qt(d.filePath,"utf-8")).split(`
|
|
194
|
+
`),m=nm(u);if(m.length===0)continue;const p=m.find(N=>N.type==="user_prompt"),f=d.stem;let g=(p==null?void 0:p.slug)||"",y=(p==null?void 0:p.timestamp)||"";y||(y=new Date(d.mtime).toISOString());let x;if(d.filePath.endsWith(".log")){d.stem.endsWith("-stale")?g=g||"rule-reflection/stale":d.stem.endsWith("-conversation")?g=g||"rule-reflection/conversation":g=g||"rule-reflection";const N=d.filePath.replace(/\.log$/,".context");if(Mt(N))try{x=await Qt(N,"utf-8")}catch{}}const v=m.filter(N=>N.type==="tool_call").length,b=m.filter(N=>N.type==="assistant_text").length;for(const N of m)N.type==="tool_call"&&N.name&&N.input&&(N.summary=Zh(N.name,N.input));if(a&&!(f.toLowerCase().includes(a)||g.toLowerCase().includes(a)||m.some(S=>rm(S,a))))continue;for(const N of m)N.type==="tool_result"&&N.content&&N.content.length>ss&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,ss));const w=em(m),C=tm(m);l.push({id:f,slug:g,timestamp:y,stats:{toolCalls:v,textBlocks:b},entries:m,context:x,ruleChanges:w,hasConfusion:C})}return Response.json({agents:l})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const sm=Object.freeze(Object.defineProperty({__proto__:null,loader:am},Symbol.toStringTag,{value:"Module"}));async function om({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=Qn(r);try{return await Ut(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error clearing log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function im({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Qn(t);try{if(!Mt(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 Qt(r,"utf-8");return!a||a.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error reading log file:",a);const s=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const lm=Object.freeze(Object.defineProperty({__proto__:null,action:om,loader:im},Symbol.toStringTag,{value:"Module"}));async function cm(e,t){var o,i,l,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Re();const r=await st({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(o=r.scenarios)==null?void 0:o.find(m=>m.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={returnValue:{status:"success",data:((d=(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=(h=a.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function dm({request:e}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return H({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await cm(r,a);return console.log("[API] Function execution completed successfully"),H({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),H({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const um=Object.freeze(Object.defineProperty({__proto__:null,action:dm},Symbol.toStringTag,{value:"Module"}));function hm({request:e}){return H({status:"ok"})}async function mm({request:e,context:t}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return console.error("[Interactive Mode API] Queue not initialized"),H({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("action"),o=a.get("analysisId"),i=a.get("scenarioId");if(!s||!o)return H({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return H({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await De();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return H({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return H({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return H({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),H({error:"Failed to control interactive mode",details:s},{status:500})}}const pm=Object.freeze(Object.defineProperty({__proto__:null,action:mm,loader:hm},Symbol.toStringTag,{value:"Module"}));async function fm({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:a}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),a&&a.length>0){const s=pe();if(s)for(const o of a){const i=le.join(s,".codeyam","captures","screenshots",o);try{await me.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 uc({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 gm=Object.freeze(Object.defineProperty({__proto__:null,action:fm},Symbol.toStringTag,{value:"Module"})),Xt="/tmp/codeyam",$r=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",_o=500,ym=_o*1024*1024;function Ct(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Sn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function xm(e){return Ct("config user.email",e)}function bm(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 vm(e,t=20){const r=ee.join(Xt,"local-dev",e,"codeyam","log.txt");if(!Q.existsSync(r))return[];try{return Q.readFileSync(r,"utf8").split(`
|
|
195
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function wm(e){try{const t=await fetch(`${$r}/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 Cm(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 Nm(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),h=ee.join(Xt,`delta-staging-${d}`),u=ee.join(h,"delta");Q.mkdirSync(u,{recursive:!0});try{const m=Ct("diff --binary HEAD",t)||"";Q.writeFileSync(ee.join(u,"tracked.patch"),m?m+`
|
|
196
|
+
`:"");const p=Ct("ls-files --others --exclude-standard",t);if(p){const x=ee.join(u,"untracked");Q.mkdirSync(x,{recursive:!0});for(const v of p.split(`
|
|
197
|
+
`).filter(Boolean)){const b=ee.join(t,v),w=ee.join(x,v);if(Q.existsSync(b)){const C=ee.dirname(w);Q.mkdirSync(C,{recursive:!0}),Q.statSync(b).isFile()&&Q.copyFileSync(b,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(s,null,2));const g=ee.join(Xt,"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
|
|
198
|
+
`);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")),o&&o.length>0&&(Q.writeFileSync(ee.join(u,"screenshot.jpg"),o),l(`Screenshot included (${Sn(o.length)})`));try{Me(`tar -czf "${a}" -C "${h}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{Q.rmSync(h,{recursive:!0,force:!0})}}async function Sm(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=Ct("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=Ct("rev-parse --abbrev-ref HEAD",t)||"unknown",h=Ct("status --porcelain",t),u=Ct("remote get-url origin",t),m=h!==null&&h.length>0,p=po(r),f=bm(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:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},x=Date.now(),v=ee.join(Xt,`base-${l}-${x}.tar.gz`),b=ee.join(Xt,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const w=await wm(l);let C=null;w?i("Server already has base, skipping..."):(i("Generating base archive..."),Cm(t,v),C=Q.statSync(v).size,i(`Base archive: ${Sn(C)}`)),i("Generating delta archive..."),Nm({projectRoot:t,projectSlug:r,outputPath:b,metadata:y,screenshot:s,onProgress:o});const S=Q.statSync(b).size;i(`Delta archive: ${Sn(S)}`);const k=(C||0)+S;if(k>ym)throw Q.existsSync(v)&&Q.unlinkSync(v),Q.unlinkSync(b),new Error(`Bundle too large: ${Sn(k)} (max: ${_o} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:w?null:v,deltaPath:b,metadata:y,baseSha:l,baseSize:C,deltaSize:S}}async function Em(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),h=Q.statSync(r),u=t?Q.statSync(t):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${$r}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:s.timestamp,git:s.git,versions:s.versions,system:s.system,feedback:s.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 v=Q.readFileSync(r);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(w=>{if(!w.ok)throw new Error(`Delta upload failed: ${w.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${$r}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const w=await b.json();throw new Error(w.error||`Confirm failed: ${b.status}`)}return t&&Q.existsSync(t)&&Q.unlinkSync(t),Q.unlinkSync(r),{bundleId:f}}async function Am({request:e}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),s=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("entityName"),m=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 k=await g.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${g.size} bytes`)}const v=pe();if(!v)return H({error:"Project root not found"},{status:500});const b=await De();if(!b)return H({error:"Project slug not found"},{status:500});const w={issueType:r||"other",description:y,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:vm(b,20),entityName:u||void 0,entityType:m||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${w.source}, issue: ${w.issueType}`);const C=await Sm({projectRoot:v,projectSlug:b,feedback:w,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),N=(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 Em({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:b,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${S.bundleId}`),H({success:!0,reportId:S.bundleId,size:N})}catch(t){return console.error("[Bundle] Error:",t),H({error:t.message||"Failed to generate bundle"},{status:500})}}function km(){const e=pe(),t=e?xm(e):null;return H({defaultEmail:t})}const Pm=Object.freeze(Object.defineProperty({__proto__:null,action:Am,loader:km},Symbol.toStringTag,{value:"Module"}));function St(){const e=process.memoryUsage(),t=fl.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(Pr.totalmem()/1024/1024),freeMemory:Math.round(Pr.freemem()/1024/1024)}}}function _m(){const e=St();console.log(`
|
|
199
|
+
[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 Mm(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=St();global.gc();const t=St(),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 Tm(){const e=St(),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 jm({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=Mm(),s=St();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:s})}case"detailed":{const a=_m();return Response.json({success:!0,stats:a})}case"leaks":{const a=Tm(),s=St();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=St();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const Im=Object.freeze(Object.defineProperty({__proto__:null,loader:jm},Symbol.toStringTag,{value:"Module"})),os=Yr(Or);async function $m({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const a=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const s=await Promise.all(a.map(async o=>{const i=Rm(o),l=i?await Dm(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:s})}function Rm(e){try{return process.kill(e,0),!0}catch{return!1}}async function Dm(e){try{const{stdout:t}=await os(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await os(`ps -p ${e} -o args=`),a=r.trim(),s=a.match(/codeyam-(\w+)/);return s?`codeyam-${s[1]}`:a.split(" ")[0]||null}catch{return null}}}const Lm=Object.freeze(Object.defineProperty({__proto__:null,loader:$m},Symbol.toStringTag,{value:"Module"})),Fm=Hn(import.meta.url),Om=ee.dirname(Fm);function Ym({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=go(),r=pe()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const a=(t==null?void 0:t.port)||3111,s=ee.join(Om,"..","..","..","..","webserver","bootstrap.js"),o=ee.join(r,".codeyam","logs");Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0});const i=Q.openSync(ee.join(o,"background-server.log"),"a"),l=Q.openSync(ee.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();Q.appendFileSync(ee.join(o,"background-server.log"),`
|
|
200
|
+
[${d}] Server restart requested via dashboard
|
|
201
|
+
`),ud();const h=Wn("node",[s],{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"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const zm=Object.freeze(Object.defineProperty({__proto__:null,action:Ym},Symbol.toStringTag,{value:"Module"}));async function Bm({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 m,p,f,g,y;const h=(p=(m=l.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[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(h)?h.length:"not-array",argumentsDataPreview:u})});const s=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await kc(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{var u,m;const h=(m=(u=l.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const Um=Object.freeze(Object.defineProperty({__proto__:null,action:Bm},Symbol.toStringTag,{value:"Module"})),Wm=()=>[{title:"CodeYam - Agent Transcripts"},{name:"description",content:"View background agent transcripts and tool call history"}];async function Hm({request:e}){try{const r=new URL(e.url).searchParams.get("search")||"",a=new URL(`/api/agent-transcripts${r?`?search=${encodeURIComponent(r)}`:""}`,e.url),o=await(await fetch(a.toString())).json();return o.error?H({agents:[],error:o.error,search:r}):H({agents:o.agents||[],error:null,search:r})}catch(t){return console.error("Failed to load agent transcripts:",t),H({agents:[],error:"Failed to load agent transcripts",search:""})}}function Jm(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function Vm(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function En({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},a={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:a[e]||e})}function Gm({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let a=typeof r=="string"?r:JSON.stringify(r);return a.length>500&&(a=a.slice(0,500)+"..."),c("div",{children:[c("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:a})]},t)})})}function qm({content:e,truncated:t,fullLength:r}){const[a,s]=_(!1);return c("div",{children:[c("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!a&&"..."]}),t&&n("button",{onClick:()=>s(!a),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:a?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Km({entry:e,pairedResult:t}){const[r,a]=_(!1),s=Jm(e.timestamp||"");return e.type==="user_prompt"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(En,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(En,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?c("div",{className:"my-2",children:[c("button",{onClick:()=>a(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(ht,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n($t,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(En,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:s})]}),r&&c("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Gm,{input:e.input||{}}),t&&c("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[c("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(qm,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Qm({change:e}){const[t,r]=_(!1),a=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return c("li",{children:[n("button",{onClick:()=>a&&r(!t),className:`text-left w-full ${a?"hover:text-green-900 cursor-pointer":""}`,children:c("span",{className:"inline-flex items-center gap-1",children:[a&&(t?n(ht,{className:"w-3 h-3 inline flex-shrink-0"}):n($t,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&c("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&c("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&c("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function Zm({changes:e}){const t=e.filter(a=>a.action==="touched"),r=e.filter(a=>a.action!=="touched");return c("div",{className:"my-2 bg-green-50 border border-green-200 rounded-md p-3",children:[n("div",{className:"text-xs font-bold text-green-800 mb-1",children:"Rule Changes:"}),c("ul",{className:"text-xs text-green-700 space-y-0.5 font-mono",children:[r.map((a,s)=>n(Qm,{change:a},s)),t.length>0&&c("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Xm({agent:e,defaultOpen:t}){const[r,a]=_(t),[s,o]=_(!1),[i,l]=_(null),d=ae(()=>{const x={};for(const v of e.entries)v.type==="tool_result"&&v.tool_use_id&&(x[v.tool_use_id]=v);return x},[e.entries]),h=ae(()=>{const x=new Set;for(const v of e.entries)v.type==="tool_call"&&v.tool_use_id&&d[v.tool_use_id]&&x.add(v.tool_use_id);return x},[e.entries,d]),u=x=>{x.stopPropagation(),o(!0),l(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(v=>v.json()).then(v=>{v.success?l(`Saved to ${v.fixturePath}`):l(`Error: ${v.error}`)}).catch(v=>{l(`Error: ${v instanceof Error?v.message:String(v)}`)}).finally(()=>{o(!1)})},m=(e.ruleChanges||[]).filter(x=>x.action!=="touched"),p=(e.ruleChanges||[]).filter(x=>x.action==="touched"),f=m.length>0,g=p.length>0,y=f||g;return c("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${f?"border-green-300":"border-gray-200"}`,children:[c("button",{onClick:()=>a(!r),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[r?n(ht,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n($t,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),f&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Fr,{className:"w-3 h-3"}),m.length===1?"1 rule changed":`${m.length} rules changed`]}),!f&&g&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[p.length," timestamp",p.length!==1?"s":""," ","touched"]}),e.hasConfusion&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(An,{className:"w-3 h-3"}),"Confusion Detected"]}),c("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks"]}),c("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[Vm(e.timestamp),f&&c("button",{onClick:u,disabled:s,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(Ri,{className:"w-3 h-3"}),s?"Saving...":"Save Fixture"]})]})]}),i&&n("div",{className:`px-4 py-2 text-xs font-mono ${i.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:i}),r&&c("div",{className:"px-4 pb-4 border-t border-gray-100",children:[y&&n(Zm,{changes:e.ruleChanges}),e.context&&c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(En,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Input context given to the agent"})]}),n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e.context})]}),e.entries.map((x,v)=>{if(x.type==="tool_result"&&x.tool_use_id&&h.has(x.tool_use_id))return null;const b=x.type==="tool_call"&&x.tool_use_id?d[x.tool_use_id]:void 0;return n(Km,{entry:x,pairedResult:b},`${e.id}-${v}`)})]})]})}const ep=$e(function(){const{agents:t,error:r,search:a}=Ye(),[s,o]=_(a),[i,l]=_(!1),[d,h]=_(0);Xe({source:"agent-transcripts-page"});const u=p=>{p.preventDefault(),window.location.href=`/agent-transcripts${s?`?search=${encodeURIComponent(s)}`:""}`},m=()=>{l(!i),h(p=>p+1)};return r?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:r})]})}):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 gap-3 mb-1",children:[n(se,{to:"/memory",className:"text-gray-400 hover:text-gray-600 transition-colors",children:n($i,{className:"w-5 h-5"})}),n(kn,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),c("div",{className:"flex items-center gap-4 mb-6",children:[c("form",{onSubmit:u,className:"relative flex-1 max-w-md",children:[n(rn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:s,onChange:p=>o(p.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:m,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:i?"Collapse All":"Expand All"})]}),c("div",{className:"text-sm text-gray-500 mb-4",children:[t.length," agent",t.length!==1?"s":""," found",a&&c("span",{children:[" ","matching “",a,"”",n(se,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(kn,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(p=>n(Xm,{agent:p,defaultOpen:i},p.id))},d)]})})}),tp=Object.freeze(Object.defineProperty({__proto__:null,default:ep,loader:Hm,meta:Wm},Symbol.toStringTag,{value:"Module"}));async function np({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:s}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!is(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 h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,l)),h=is(r);if(h){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(s)try{await dt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function is(e){try{return process.kill(e,0),!0}catch{return!1}}const rp=Object.freeze(Object.defineProperty({__proto__:null,action:np},Symbol.toStringTag,{value:"Module"})),ap=Hn(import.meta.url),sp=le.dirname(ap),ls="/tmp/claude-rule-markers",op=le.resolve(sp,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function ip(e){const t=[],r=new Set;for(const a of e.split(`
|
|
202
|
+
`)){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const d=l;if(d.type!=="tool_use")continue;const h=String(d.name||""),u=d.input||{};if(h==="Write"||h==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const p=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${h}:${p}`;r.has(f)||(r.add(f),t.push({action:h==="Write"?"created":"modified",filePath:p}))}}else if(h==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const p=`touch:${m}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:m}))}}}}return t}async function lp({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const a=le.join(ls,`${r}.log`);if(!Mt(a))return Response.json({error:`Log file not found: ${a}`},{status:404});const s=await Qt(a,"utf-8"),o=le.join(ls,`${r}.context`);let i=null;if(Mt(o))try{i=await Qt(o,"utf-8")}catch{}const l=ip(s),h=i?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(g=>i.toLowerCase().includes(g)):!1,u=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":"",m=r.slice(0,8)+u,p=le.join(op,m);await nl(p,{recursive:!0}),await Ut(le.join(p,"agent-log.jsonl"),s),i&&await Ut(le.join(p,"context.md"),i),await Ut(le.join(p,"rule-changes.json"),JSON.stringify(l,null,2)),await Ut(le.join(p,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:l.length},null,2));const f=le.relative(process.cwd(),p);return console.log(`[api.save-fixture] Saved fixture to ${f}`),Response.json({success:!0,fixturePath:f})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const cp=Object.freeze(Object.defineProperty({__proto__:null,action:lp},Symbol.toStringTag,{value:"Module"}));async function dp({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=pe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=le.join(r,".codeyam","captures","screenshots",t);try{await me.access(a);const s=await me.readFile(a),o=le.extname(a).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(s,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const up=Object.freeze(Object.defineProperty({__proto__:null,loader:dp},Symbol.toStringTag,{value:"Module"})),cs={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function na({type:e,className:t=""}){const r=cs[e]||cs.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const hp={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 bn({variant:e,pid:t,label:r,className:a=""}){const s=hp[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${a}`,style:{backgroundColor:s.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:s.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:s.textColor},children:o})})}function Oe({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=_("loading"),[l,d]=_(!1),h=ve(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ne(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:h,src:u,alt:r,onLoad:m,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let ds=!1;function mp(){if(ds)return;const e=document.createElement("style");e.textContent=`
|
|
203
|
+
@keyframes strongPulse {
|
|
204
|
+
0%, 100% { opacity: 0.2; }
|
|
205
|
+
50% { opacity: 1; }
|
|
206
|
+
}
|
|
207
|
+
`,document.head.appendChild(e),ds=!0}function ra({size:e="medium",className:t=""}){typeof document<"u"&&mp();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:s,gap:o}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function pp({request:e,context:t,params:r}){var Y,L,I,E,U,W,$,K;let a=t.analysisQueue;a||(a=await it());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return H({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),h=await De();let u=null;if(h&&((Y=d==null?void 0:d.currentlyExecuting)!=null&&Y.commitSha)){const{project:G,branch:z}=await Te(h),B=await jn({projectId:G.id,branchId:z.id,shas:[d.currentlyExecuting.commitSha]});u=B&&B.length>0?B[0]:null}else u=await Dt();const m=async G=>{const z=await jt(G);if(!z)return null;const{getAnalysesForEntity:B}=await Promise.resolve().then(()=>zc),Z=await B(G,!1);return{...z,analyses:Z||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async G=>{const z=[];if(G.entityShas&&G.entityShas.length>0){const B=G.entityShas.map(V=>m(V)),Z=await Promise.all(B);z.push(...Z.filter(V=>V!==null))}return{...G,entities:z}}));let f=null;if(d!=null&&d.currentlyExecuting){const G=d.currentlyExecuting,z=[];if(G.entityShas&&G.entityShas.length>0){const B=G.entityShas.map(V=>m(V)),Z=await Promise.all(B);z.push(...Z.filter(V=>V!==null))}f={...G,entities:z}}const g=f?p.filter(G=>G.id!==f.id):p,y=((I=(L=u==null?void 0:u.metadata)==null?void 0:L.currentRun)==null?void 0:I.currentEntityShas)||[],v=(await Promise.all(y.map(G=>m(G)))).filter(G=>G!==null),b=[];if(h)try{const{project:G,branch:z}=await Te(h),B=await jn({projectId:G.id,branchId:z.id,limit:100});for(const Z of B){const V=((E=Z.metadata)==null?void 0:E.historicalRuns)||[];b.push(...V)}}catch(G){console.error("[activity.tsx] Failed to load historical runs from commits:",G)}const w=[...b].sort((G,z)=>{const B=G.lastCaptureAt||G.analysisCompletedAt||G.archivedAt||G.createdAt||"";return(z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"").localeCompare(B)}),C=(o-1)*i,N=C+i,S=w.slice(C,N),k=Math.ceil(w.length/i),M=await Promise.all(S.map(async G=>{const z=G.currentEntityShas||[];if(z.length===0)return{...G,entities:[]};const B=await Promise.all(z.map(Z=>m(Z)));return{...G,entities:B.filter(Z=>Z!==null)}})),j=!!f,R=g.length,O=w.filter(G=>{const z=!!G.failedAt,B=G.readyToBeCaptured,Z=G.capturesCompleted??0,V=B===void 0?!0:B===0||Z>=B;return!z&&!!G.analysisCompletedAt&&V}),P=new Set(((U=f==null?void 0:f.entities)==null?void 0:U.map(G=>G.sha))||[]),A=O.filter(G=>!(G.currentEntityShas||[]).some(B=>P.has(B))),F=(await Promise.all(A.slice(0,3).map(async G=>{const z=G.currentEntityShas||[];if(z.length===0)return{run:G,entities:[]};const B=await Promise.all(z.map(Z=>m(Z)));return{run:G,entities:B.filter(Z=>Z!==null)}}))).flatMap(({run:G,entities:z})=>z.map(B=>({...B,runId:G.id,completedAt:G.lastCaptureAt||G.analysisCompletedAt||G.archivedAt||G.createdAt})));let q=[],J=null,D=null;if(($=(W=u==null?void 0:u.metadata)==null?void 0:W.currentRun)!=null&&$.analysisCompletedAt&&v.length>0){const G=v[0].sha;J=v[0];const z=await qn(G);z&&z.length>0&&z[0].scenarios&&(q=z[0].scenarios,D=z[0].status)}return H({state:{...d,jobs:g,currentlyExecuting:f},currentRun:(K=u==null?void 0:u.metadata)==null?void 0:K.currentRun,historicalRuns:M,totalHistoricalRuns:w.length,currentPage:o,totalPages:k,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:v,tab:l,hasCurrentActivity:j,queuedCount:R,recentCompletedEntities:F,hasMoreCompletedRuns:A.length>3,currentEntityScenarios:q,currentEntityForScenarios:J,currentAnalysisStatus:D})}function fp({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:s.map(o=>{const i=e===o.id;return n(se,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
208
|
+
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
209
|
+
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
210
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
211
|
+
inline-block w-2 h-2 rounded-full
|
|
212
|
+
${i?"":"bg-gray-400"}
|
|
213
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function gp({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var T,F,q,J;const[m,p]=_({}),[f,g]=_({isKilling:!1,current:0,total:0}),y=rt(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),w=b&&!!(t!=null&&t.capturePid),C=!b,N=x,S=d||[],{lastLine:k}=ft(a,N);ne(()=>{if(!t)return;const D=[t.analyzerPid,t.capturePid].filter(E=>!!E);if(D.length===0)return;let Y=!0;const L=async()=>{try{const U=await(await fetch(`/api/process-status?pids=${D.join(",")}`)).json();if(U.processes&&Y){const W={};U.processes.forEach($=>{W[$.pid]={isRunning:$.isRunning,processName:$.processName}}),p(W)}}catch(E){Y&&console.error("Failed to fetch process statuses:",E)}};L();const I=setInterval(()=>void L(),5e3);return()=>{Y=!1,clearInterval(I)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[M,j]=_(!1),[R,O]=_(!1);ne(()=>{v.length<=3&&M&&j(!1)},[v.length,M]),ne(()=>{i.length<=3&&R&&O(!1)},[i.length,R]);const P=M?v:v.slice(0,3),A=v.length>3;return c("div",{className:"flex flex-col gap-[45px]",children:[N?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(D=>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(We,{type:D.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col gap-[1px]",children:[c("div",{className:"flex items-center gap-[14px]",children:[n(se,{to:`/entity/${D.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:D.name}),D.entityType&&n(na,{type:D.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:D.filePath,children:D.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},D.sha)),A&&!M&&c("button",{onClick:()=>j(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),M&&A&&n("button",{onClick:()=>j(!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&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(D=>{var $,K,G,z;if(!D.id)return null;const Y=(K=($=D.metadata)==null?void 0:$.screenshotPaths)==null?void 0:K[0],L=(G=D.metadata)==null?void 0:G.noScreenshotSaved,I=Y&&!L,E=(z=u==null?void 0:u.scenarios)==null?void 0:z.find(B=>B.name===D.name),W=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt||!I&&!L;return n(se,{to:`/entity/${h.sha}/scenarios/${D.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:I?n(Oe,{screenshotPath:Y,alt:D.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(ra,{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"})},D.id)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&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(bn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||((T=m[t.analyzerPid])==null?void 0:T.isRunning))&&n(bn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(bn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(w||((F=m[t.capturePid])==null?void 0:F.isRunning))&&n(bn,{variant:"running"})]}),(((q=m[t==null?void 0:t.analyzerPid])==null?void 0:q.isRunning)||((J=m[t==null?void 0:t.capturePid])==null?void 0:J.isRunning))&&n("button",{onClick:()=>{const D=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(I=>{var E;return!!I&&((E=m[I])==null?void 0:E.isRunning)});if(D.length===0)return;const Y=D.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${Y})?`))return;g({isKilling:!0,current:1,total:D.length}),(async()=>{for(let I=0;I<D.length;I++){const E=D[I];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:E,commitSha:s||""})})}catch(U){console.error(`Failed to kill process ${E}:`,U)}I<D.length-1&&g({isKilling:!0,current:I+2,total:D.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(ks,{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(se,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(se,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),c(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&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:[(R?i:i.slice(0,3)).map(D=>{var I;const Y=(I=D.analyses)==null?void 0:I[0],L=(Y==null?void 0:Y.scenarios)||[];return Y==null||Y.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(We,{type:D.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(se,{to:`/entity/${D.sha}`,className:"hover:underline cursor-pointer",title:D.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:D.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:D.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:D.filePath,children:D.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:E=>{E.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:E=>{E.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),L.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:L.map(E=>{var K,G,z;if(!E.id)return null;const U=(G=(K=E.metadata)==null?void 0:K.screenshotPaths)==null?void 0:G[0],W=(z=E.metadata)==null?void 0:z.noScreenshotSaved,$=U&&!W;return c("div",{className:"shrink-0 flex flex-col gap-2",children:[n(se,{to:`/entity/${D.sha}/scenarios/${E.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:$?"#f3f4f6":"#FAFAFA",borderColor:$?"#d1d5db":"#BCCDD3",borderStyle:$?"solid":"dashed"},onMouseEnter:B=>{$&&(B.currentTarget.style.borderColor="#005C75",B.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:B=>{B.currentTarget.style.borderColor=$?"#d1d5db":"#BCCDD3",B.currentTarget.style.boxShadow="none"},children:$?n(Oe,{screenshotPath:U,alt:E.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E.name})]},E.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},D.sha)}),i.length>3&&!R&&c("button",{onClick:()=>O(!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"]}),R&&i.length>3&&n("button",{onClick:()=>O(!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 yp({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(Di,{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(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[a,s]=_(null),[o,i]=_(null),[l,d]=_(null),[h,u]=_(!1),[m,p]=_(!1),[f,g]=_(new Set),y=rt();ne(()=>{e.length<=3&&m&&p(!1)},[e.length,m]);const x=S=>{s(S)},v=(S,k)=>{S.preventDefault(),i(k)},b=async(S,k)=>{if(S.preventDefault(),!a){i(null);return}const M=e.findIndex(O=>O.id===a);if(M===-1){s(null),i(null);return}if(M===k){s(null),i(null);return}const j=M<k?"down":"up",R=Math.abs(k-M);u(!0);try{for(let O=0;O<R;O++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:j})});y.revalidate()}catch(O){console.error("Failed to reorder job:",O)}finally{u(!1),s(null),i(null)}},w=()=>{h||(s(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(k){console.error("Failed to cancel job:",k)}},N=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 N(),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:[(m?e:e.slice(0,3)).map(S=>{var A,T,F,q;const k=e.findIndex(J=>J.id===S.id),M=l===k,j=a===S.id,R=o===k,O=f.has(S.id),P=((A=S.entities)==null?void 0:A.length)>0?O?S.entities:S.entities.slice(0,3):[];return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:j||h?.5:1,transform:R&&a!==null&&!j?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":j?"grabbing":"grab"},onMouseEnter:()=>d(k),onMouseLeave:()=>d(null),draggable:!h,onDragStart:J=>{x(S.id),J.dataTransfer.effectAllowed="move"},onDragOver:J=>v(J,k),onDrop:J=>void b(J,k),onDragEnd:w,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Li,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),c("div",{className:"flex flex-col gap-2 mt-8",children:[P.length>0?c(ce,{children:[P.map(J=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(We,{type:J.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${J.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:J.name}),J.entityType&&n(na,{type:J.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:J.filePath})]})]})})},J.sha)),((T=S.entities)==null?void 0:T.length)>3&&n("button",{onClick:()=>{g(J=>{const D=new Set(J);return D.has(S.id)?D.delete(S.id):D.add(S.id),D})},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:O?"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(Pn,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((F=S.entityNames)==null?void 0:F[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:((q=S.filePaths)==null?void 0:q[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:[M&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Fi,{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&&!m&&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"]}),m&&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 xp({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){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(Oi,{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(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=_(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{d.push({...m,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return c("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var g;const m=(g=u.analyses)==null?void 0:g[0],p=(m==null?void 0:m.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(We,{type:u.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),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,N;if(!y.id)return null;const x=(C=(w=y.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],v=(N=y.metadata)==null?void 0:N.noScreenshotSaved,b=x&&!v;return n(se,{to:`/entity/${u.sha}/scenarios/${y.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(Oe,{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 bp=$e(function(){const t=Ye(),r=Ss(),[a,s]=_(!1);Xe({source:"activity-page"});const o=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(fp,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(gp,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(yp,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(xp,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n(ut,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),vp=Object.freeze(Object.defineProperty({__proto__:null,default:bp,loader:pp},Symbol.toStringTag,{value:"Module"}));async function Mo(e,t,r){var C,N;await Re();const a=await st({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=pe();if(!s)throw new Error("Project root not found");const o=ee.join(s,".codeyam","config.json"),i=JSON.parse(Q.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=Qn(l);try{Q.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Te(l),u=((C=h.metadata)==null?void 0:C.packageManager)||"npm",m=3112,p=ot(l),f=((N=h.metadata)==null?void 0:N.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=cc({filePath:a.filePath,webapps:f,environmentVariables:g,port:m,packageManager:u});await Rt(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const k of S.scenarios)(!t||k.name===t)&&(delete k.screenshotStartedAt,delete k.screenshotFinishedAt,delete k.interactiveStartedAt,delete k.interactiveFinishedAt,delete k.error,delete k.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),v=y.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content: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:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:l,port:m,packageManager:u,framework:y.framework,instructions:b}}async function wp({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),s=r.searchParams.get("scenarioId")||void 0;if(!a)return H({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await it()),!o)return H({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Mo(a,s,o);return H({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),H({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Cp({request:e,context:t}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return H({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return H({error:"Missing required field: analysisId"},{status:400});const i=await Mo(s,o,r);return H({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),H({error:"Failed to setup debug environment",details:s},{status:500})}}const Np=Object.freeze(Object.defineProperty({__proto__:null,action:Cp,loader:wp},Symbol.toStringTag,{value:"Module"}));async function Sp({request:e,context:t}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return H({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return H({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return H({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const l=await Hh(s,i,r);return console.log("[API] Recapture queued",l),H({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),H({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Ep=Object.freeze(Object.defineProperty({__proto__:null,action:Sp},Symbol.toStringTag,{value:"Module"}));function Ap(e,t){var i,l,d,h,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||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 s=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||s){const m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}: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 kp(e){return Ap(e).hasOutdatedSimulations}function nr(e,t,r,a,s){var J,D,Y,L,I,E,U,W;const o=(J=t==null?void 0:t.scenarios)==null?void 0:J.find($=>$.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,m=l&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((Y=(D=e.metadata)==null?void 0:D.screenshotPaths)!=null&&Y[0])||!!((L=e.metadata)!=null&&L.executionResult),f=l&&!d,g=o==null?void 0:o.error,y=(E=(I=e.metadata)==null?void 0:I.executionResult)==null?void 0:E.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const $ of t.errors)x.push({source:`${$.phase} phase`,message:$.message});if(t!=null&&t.steps)for(const $ of t.steps)$.error&&x.push({source:$.name,message:$.error});const v=!p&&!g&&!y&&x.length>0,b=!!(g||y||m||v),w=m?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(v?`Analysis error: ${x[0].message}`:null),C=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(y==null?void 0:y.stack)||null,S=(a&&s?s.jobs.some($=>{var K;return((K=$.entityShas)==null?void 0:K.includes(a))||$.type==="analysis"&&$.entityShas&&$.entityShas.length===0})||((W=(U=s.currentlyExecuting)==null?void 0:U.entityShas)==null?void 0:W.includes(a)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,k=i&&!l&&!h&&!b,M=(S||k||f)&&!b,j=(S||k)&&r===!1&&!p;let R;j?R="crashed":b?R="error":p||h?R="completed":f?R="capturing":k?R="starting":S?R="queued":R="pending";let O="📷",P="pending",A=!1,T=`Not captured: ${e.name}`;const F="border-gray-300",q=b||j?"bg-red-50":"bg-white";return b||j?(O="⚠️",P="error",T=`Error: ${j?"Analysis process crashed":w||"Unknown error"}`):S?(O="⋯",P="queued",T=`Queued: ${e.name}`):k?(O="⋯",P="starting",A=!0,T=`Starting server for ${e.name}...`):f&&!b?(O="⋯",P="capturing",A=!0,T=`Capturing ${e.name}...`):p&&(O="✓",P="completed",T=e.name),{hasError:b||j,errorMessage:j?"Analysis process crashed":w,errorStack:j?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:p,hasCrashed:j,isAnalyzing:M,isQueued:S,isServerStarting:k,status:R,icon:O,iconType:P,shouldSpin:A,title:T,borderColor:F,bgColor:q}}function To({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var C,N,S,k,M,j;const o=nr(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,l=!!i,h=(((S=(N=e.metadata)==null?void 0:N.data)==null?void 0:S.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((M=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:M.length)||0,p=((j=i==null?void 0:i.timing)==null?void 0:j.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?s?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=a?`border-2 ${x.border}`:"",b=Array.from({length:3},(R,O)=>n("div",{className:`w-1 h-1 rounded-full ${O<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},O)),w=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
214
|
+
${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
|
|
215
|
+
${p}ms`:`Not executed: ${e.name}`;return c(se,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:w,onClick:R=>R.stopPropagation(),children:[n("div",{className:`${x.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),l&&!o.hasError&&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&&!o.hasError&&m>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function Rr({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 us({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){var y,x;if(t.entityType==="library")return n(To,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=nr(e,r,s,t.sha,a),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${l}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return n(se,{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(Oe,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(ra,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Rr,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Yi,{...v});default:return b}};return n(se,{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:m.iconSize,children:g()})})}const _t=70;function Pp({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:s,cacheBuster:o,activeTab:i,entityType:l,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:g,isBreakdownView:y}){var A,T,F,q,J,D;const x=ve(null),[v,b]=_(new Set),[w,C]=_(!1);ne(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const N=Y=>`/entity/${s}/scenarios/${Y}`,S=Y=>{b(L=>{const I=new Set(L);return I.has(Y)?I.delete(Y):I.add(Y),I})},k=(Y,L=2)=>{const E=Y.split(`
|
|
216
|
+
`).slice(0,L).join(" ").trim();return E.length>_t?E.substring(0,_t-3):(Y.split(`
|
|
217
|
+
`).length>L||Y.length>E.length,E)},M=ae(()=>{var L;if(!((L=r==null?void 0:r.metadata)!=null&&L.executionFlows)||!(r!=null&&r.scenarios))return null;const Y=r.scenarios.filter(I=>{var E;return!((E=I.metadata)!=null&&E.sameAsDefault)});return Xr(r.metadata.executionFlows,Y)},[r]),j=(M==null?void 0:M.totalFlows)||0,R=(M==null?void 0:M.coveredFlows)||0,O=(M==null?void 0:M.coveragePercentage)||0;(A=d==null?void 0:d.metadata)!=null&&A.defaultWidth||(T=r==null?void 0:r.metadata)!=null&&T.defaultWidth;const P=(F=r==null?void 0:r.status)!=null&&F.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return 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(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(O),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),c(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[R,"/",j]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),c(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((D=e[0])==null?void 0:D.id)}`:`/entity/${s}/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(se,{to:`/entity/${s}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&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})]}),m&&(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((Y,L)=>{const I=!y&&(a==null?void 0:a.id)===Y.id,E=v.has(Y.id||"");return Y.id?c(se,{to:N(Y.id),ref:I?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${I?"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(us,{scenario:Y,entity:{sha:s,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${E?"":"line-clamp-1"}`,children:Y.name}),Y.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[E?Y.description:k(Y.description),!E&&Y.description.length>_t&&c(ce,{children:["...",n("button",{onClick:U=>{U.preventDefault(),U.stopPropagation(),S(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),E&&Y.description.length>_t&&n("button",{onClick:U=>{U.preventDefault(),U.stopPropagation(),S(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})}),t.length>0&&!(m&&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((Y,L)=>{const I=!y&&(a==null?void 0:a.id)===Y.id,E=v.has(Y.id||"");return Y.id?c(se,{to:`/entity/${s}/scenarios/${Y.id}`,ref:I?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${I?"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(us,{scenario:Y,entity:{sha:s,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${E?"":"line-clamp-1"}`,children:Y.name}),Y.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[E?Y.description:k(Y.description),!E&&Y.description.length>_t&&c(ce,{children:["...",n("button",{onClick:U=>{U.preventDefault(),U.stopPropagation(),S(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),E&&Y.description.length>_t&&n("button",{onClick:U=>{U.preventDefault(),U.stopPropagation(),S(Y.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})]})]})]})}function _p({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,g]=_(""),y=async()=>{await r(f)},x=async v=>{await a(f,v),v||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(se,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),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:v=>g(v.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),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:s,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(se,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),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"}),o&&c(ce,{children:[h?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 o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function Mp({scenario:e,analysis:t,entity:r}){var i,l,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],o=h=>{var g,y,x;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((g=h.sideEffects)==null?void 0:g.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const p=((y=h.sideEffects)==null?void 0:y.fileWrites)||[];p.length>0&&(u.push(`
|
|
218
|
+
File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=h.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
219
|
+
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),h.error&&u.push(`
|
|
220
|
+
Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
221
|
+
`)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const wt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function vn({scenarioId:e,analysisId:t}){const[r,a]=_(!1),[s,o]=_(!1),[i,l]=_(null),[d,h]=_(!1),u=e||t;if(!u)return null;const m=`/codeyam:diagnose ${u}`,p=async()=>{o(!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{o(!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:wt.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:wt.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:wt.commandBoxBg,borderColor:wt.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:wt.commandBoxText},children:m}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":wt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(nn,{size:14}):n(qt,{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:s,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:wt.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(Ds,{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 hs=1440,wn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],nt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function jo({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var Z,V,X,ue,he,ye,be,Se,we,ke,je;const m=Ae(),[p,f]=_(!1),[g,y]=_(!1),[x,v]=_({name:"Desktop",width:hs,height:900}),[b,w]=_(hs),[C,N]=_(1),{customSizes:S,addCustomSize:k,removeCustomSize:M}=bo(l),j=ae(()=>[...wn,...S],[S]),R=(xe,Le)=>{w(xe);const Pe=j.find(Ne=>Ne.width===xe&&Ne.height===Le);v({name:(Pe==null?void 0:Pe.name)||"Custom",width:xe,height:Le})},O=xe=>{w(xe.width),v({name:xe.name,width:xe.width,height:xe.height})},P=xe=>{k(xe,x.width,x.height??900),y(!1),v(Le=>({...Le,name:xe}))},A=(xe,Le)=>{w(xe);const Pe=j.find(Ne=>Ne.width===xe&&Ne.height===Le);v(Ne=>({name:(Pe==null?void 0:Pe.name)||"Custom",width:xe,height:Ne.height}))},T=(V=(Z=e==null?void 0:e.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:V[0],F=ae(()=>e?nr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),q=ae(()=>{var Le,Pe;const xe=[];if((Le=t==null?void 0:t.status)!=null&&Le.errors&&t.status.errors.length>0)for(const Ne of t.status.errors)xe.push({source:`${Ne.phase} phase`,message:Ne.message,stack:Ne.stack});if((Pe=t==null?void 0:t.status)!=null&&Pe.steps)for(const Ne of t.status.steps)Ne.error&&xe.push({source:Ne.name,message:Ne.error,stack:Ne.errorStack});return xe},[(X=t==null?void 0:t.status)==null?void 0:X.errors,(ue=t==null?void 0:t.status)==null?void 0:ue.steps]),J=(F==null?void 0:F.errorMessage)||null,D=(F==null?void 0:F.errorStack)||null,{interactiveServerUrl:Y,isStarting:L,isLoading:I,showIframe:E,iframeKey:U,onIframeLoad:W}=dn({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"}),$=ae(()=>Y||null,[Y]),K=!i&&o&&e&&!((ye=(he=e.metadata)==null?void 0:he.screenshotPaths)!=null&&ye[0])&&((Se=(be=t==null?void 0:t.status)==null?void 0:be.scenarios)==null?void 0:Se.some(xe=>xe.name===e.name&&xe.screenshotStartedAt&&!xe.screenshotFinishedAt)),{lastLine:G}=ft(l,i||a==="interactive"||K||!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:K?"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."}),G&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:G}),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(ut,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(q.length>0){const xe=q.length===1?((we=q[0])==null?void 0:we.message)||"An error occurred during analysis.":`${q.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:nt.background,border:`2px solid ${nt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(Rr,{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:nt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",xe," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:nt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(vn,{analysisId:t==null?void 0:t.id})})]})}),p&&l&&n(ut,{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:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(ce,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
222
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
223
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
224
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
225
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
226
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||K&&!T)&&!J&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children: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:K?`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:K?`Taking screenshots for ${((ke=t==null?void 0:t.scenarios)==null?void 0:ke.length)||0} scenario${((je=t==null?void 0:t.scenarios)==null?void 0:je.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]})]}),G&&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:G,children:G})]})]})}),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"&&(T||J)||a==="interactive"&&($||L)||a==="data"?c(ce,{children:[J&&!T&&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:nt.background,border:`2px solid ${nt.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:nt.text},children:[n(Rr,{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:nt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:nt.text},children:J})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(vn,{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:[$&&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(qd,{presets:[...wn],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:C,onSizeChange:R,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:M}),e&&r&&c(se,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),$&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${wn[wn.length-1].width}px`,width:"100%"},children:n(yo,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:O,devicePresets:j})})}),n(er,{scenarioId:e.id,scenarioName:e.name,iframeUrl:$,isStarting:L,isLoading:I,showIframe:E,iframeKey:U,onIframeLoad:W,onScaleChange:N,onDimensionChange:A,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(Mp,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(T||!J)&&n(Oe,{screenshotPath:T,cacheBuster:s,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!T?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children: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."]}),G&&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:G})]}),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"})]})]})})}):J?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(se,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children: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:J})})]}),D&&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:D})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(vn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):q.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children: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:q,title:"Analysis Error",description:q.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${q.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(vn,{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(ut,{projectSlug:l,onClose:()=>f(!1)}),g&&n(xo,{width:x.width,height:x.height??900,onSave:P,onCancel:()=>y(!1)})]})}function Tp({analysis:e,entitySha:t}){rt();const[r,a]=_(e);ne(()=>{a(e)},[e]);const[s,o]=_(null),i=ae(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return Xr(r.metadata.executionFlows,u)},[r]),l=ae(()=>i?mu(i):[],[i]),d=ae(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),h=u=>{var p;const m=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children: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(se,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,g,y;const m=(g=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0],p=h(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(Oe,{screenshotPath:m,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(se,{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(se,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),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 m=s===u.id,p=u.usedInScenarios.length>0;return c("div",{children:[n("button",{onClick:()=>o(m?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children: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:m?"▼":"▶"}),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})]})]})}),m&&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 ms({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 jp({entity:e,history:t}){const[r,a]=_("entity"),[s,o]=_(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ae(()=>{const u=new Map;return t.forEach(m=>{m.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:m,analysis:p,scenario:g})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,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,h=u=>{o(m=>{const p=new Set(m);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,m)=>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(se,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var y;const g=(p.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:g.length===0?n(ms,{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,v)=>{var C,N;const b=(N=(C=x.metadata)==null?void 0:C.screenshotPaths)==null?void 0:N[0],w=`${x.name}-${v}`;return c(se,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Oe,{screenshotPath:b,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(ms,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,m)=>{const p=s.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,v)=>{var k,M;const{version:b,analysis:w,scenario:C}=x,N=(M=(k=C.metadata)==null?void 0:k.screenshotPaths)==null?void 0:M[0],S=v===0;return c("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(se,{to:`/entity/${b.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:N?n(Oe,{screenshotPath:N,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:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),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(se,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),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"})]})]},`${b.sha}-${v}`)}),g>0&&c("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${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 ps({entity:e,analysisInfo:t,from:r}){const a=Ae(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(se,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children: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(Oe,{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(We,{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(We,{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"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?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"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const fs=e=>{var s,o,i;const t=((s=e.analysisStatus)==null?void 0:s.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function Ip({importedEntities:e,importingEntities:t}){const[r]=tn(),a=r.get("from"),s=Ae(),o=s.state!=="idle",i=e.length>0,l=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=p=>{const f=d(p);f.length!==0&&s.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,m=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:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(ps,{entity:p,analysisInfo:fs(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."})]}),m&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(ps,{entity:p,analysisInfo:fs(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 $p({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Ip,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Rp({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(en,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function en({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,l]=_(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((h,u)=>n("div",{className:"py-0.5",children:n(en,{data:h,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=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:[h.length,"}"]})]}),i?c(ce,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],g=u(f),y=m(f);return n("div",{className:"py-0.5",children:g?n(aa,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(sa,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(ce,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(en,{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 aa({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=_(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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(ce,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n(aa,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):m?n(sa,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):c(ce,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(en,{data:h,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function sa({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=_(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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(ce,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const h=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:h?n(aa,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(sa,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):n(en,{data:l,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Er({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function gs({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 ys({call:e,scenarioName:t}){const[r,a]=_(!1),[s,o]=_("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(" / ")},h=ae(()=>{var p,f,g,y,x;try{const v=JSON.parse(e.response);return(g=(f=(p=v.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&g.content?v.choices[0].message.content:(x=(y=v.content)==null?void 0:y[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=ae(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=ae(()=>{var 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}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),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:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),s==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),s==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),s==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const xs=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Dp({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var w,C,N,S,k,M,j,R,O;const[o,i]=_("entity"),[l,d]=_("analysis"),[h,u]=_(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=_("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ae(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const P=[...s.entityCalls,...s.analysisCalls],A=P.filter(F=>F.object_type==="entity"||xs.includes(F.prompt_type)),T=P.filter(F=>F.object_type!=="entity"&&!xs.includes(F.prompt_type));return A.sort((F,q)=>q.created_at-F.created_at),T.sort((F,q)=>q.created_at-F.created_at),{entityLlmCalls:A,scenarioLlmCalls:T,totalLlmCalls:P.length}},[s]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(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=(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure)==null?void 0:S.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(k=t==null?void 0:t.metadata)==null?void 0:k.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(M=e==null?void 0:e.metadata)==null?void 0:M.importedExports,"External Dependencies":(j=e==null?void 0:e.metadata)==null?void 0:j.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(R=t==null?void 0:t.metadata)==null?void 0:R.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(P=>P.data!==void 0&&P.data!==null).length;let b=null;if(o==="entity"){const P=x.find(A=>A.id===l);P&&P.data!==void 0&&P.data!==null&&(b={title:P.title,description:P.description,data:P.data})}else if(o==="scenarios"&&h){const P=r.find(A=>(A.id||A.name)===h.scenarioId);P&&(b={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(Er,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Er,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Er,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((O=t==null?void 0:t.metadata)==null?void 0:O.analyzerVersion)&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(P=>n(ys,{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(ys,{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:o==="entity"?c(ce,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(P=>{const A=P.data!==void 0&&P.data!==null;return n(gs,{label:P.title,isActive:l===P.id,onClick:()=>d(P.id),disabled:!A},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 A=P.id||P.name,T=(h==null?void 0:h.scenarioId)===A;return n(gs,{label:P.name,isActive:T,onClick:()=>u({scenarioId:A})},A)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(Lp,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(bs,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(bs,{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 bs({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 Lp({title:e,description:t,data:r}){const[a,s]=_(!0),[o,i]=_("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:()=>s(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>s(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:o})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(Rp,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Fp({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=Ae();return ne(()=>{if(e!=null&&e.sha&&s.state==="idle"&&!s.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(Dp,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function Io({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[d,h]=_(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{h(!0),setTimeout(()=>h(!1),s)}).catch(m=>{console.error("Failed to copy:",m)})},[e,s]);return n("button",{onClick:u,className:`cursor-pointer ${a}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(nn,{size:l,className:"text-green-500"}):n(qt,{size:l}):d?r:t})}const Op={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Yp={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},zp=2e3,Bp=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 Up({entity:e,entityCode:t}){const r=zn(),a=ve(null);return ne(()=>{const s=r.hash;if(!s||!a.current)return;const o=s.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!a.current)return;const 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(Io,{content:t,label:"Copy Code",duration:zp,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(gl,{language:Bp(e==null?void 0:e.filePath),style:yl,showLineNumbers:!0,customStyle:Op,lineNumberStyle:Yp,wrapLines:!0,lineProps:s=>({"data-line-number":s,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Wp=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Hp({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:s,defaultShouldRevalidate:o}){return r.pathname===a.pathname&&r.search===a.search?o:!!(e.sha!==t.sha||s)}async function Jp({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",h=l[1]||null,u=l[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,g,y,x]=await Promise.all([jt(a),De(),Dt(),Uc(pe()||process.cwd())]),v=f?await Vr(f):null,b=f?await Xs(f.sha):null;let w={importedEntities:[],importingEntities:[]},C=null,N=[];f&&(w=await eo(f),C=await to(f),N=await ro(f));const S=!!(f&&N.length>0&&N[0].sha!==f.sha),k=N.length>0?N[0].sha:null,M=!!(N.length>0&&N[0].analyses&&N[0].analyses.length>0),j=f?await no(f):!1;return H({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:g,from:o,relatedEntities:w,entityCode:C??void 0,hasNewerVersion:S,newestEntitySha:k,newestVersionHasAnalysis:M,fileModifiedSinceEntity:j,history:N,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:x,queueState:p})}const Vp=$e(function(){var ga,ya,xa,ba,va,wa,Ca,Na,Sa,Ea,Aa,ka,Pa,_a,Ma;const t=Ye(),s=(Ss()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,l=s[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,m=u||h,p=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,w=t.history,C=t.currentCommit,N=t.hasAnApiKey,S=t.queueState;(ga=m==null?void 0:m.status)==null||ga.errors;const k=(m==null?void 0:m.scenarios)||[],M=k.filter(re=>{var fe;return!((fe=re.metadata)!=null&&fe.sameAsDefault)}),j=k.filter(re=>{var fe;return(fe=re.metadata)==null?void 0:fe.sameAsDefault}),R=It(),O=ve(null);ne(()=>{O.current===null&&(O.current=window.history.length)},[]);const P=()=>{if(typeof window>"u")return;const re=window.history.state;if(re===null||(re==null?void 0:re.idx)===void 0||(re==null?void 0:re.idx)===0)R("/");else{const fe=window.history.length,Ue=O.current;if(Ue!==null&&fe>Ue){const Ee=fe-Ue+1;R(-Ee)}else R(-1)}},A=!!S.currentlyExecuting,T=o,F=(ya=C==null?void 0:C.metadata)==null?void 0:ya.currentRun,q=!!(F!=null&&F.createdAt)&&!(F!=null&&F.analysisCompletedAt),J=!!(d!=null&&d.sha&&((xa=F==null?void 0:F.currentEntityShas)!=null&&xa.includes(d.sha))),D=!!(d!=null&&d.sha&&((va=(ba=S.currentlyExecuting)==null?void 0:ba.entityShas)!=null&&va.includes(d.sha))),Y=!!(d!=null&&d.sha&&((wa=S.jobs)!=null&&wa.some(re=>{var fe;return(fe=re.entityShas)==null?void 0:fe.includes(d.sha)}))),L=J||D||Y,I=L&&((Ca=m==null?void 0:m.status)==null?void 0:Ca.finishedAt)!=null&&M.length>0&&m.entitySha!==(d==null?void 0:d.sha),E=ae(()=>{if(T!=="scenarios")return null;if(i){const re=M.find(fe=>fe.id===i);if(re)return re}return M.length>0&&!L?M[0]:null},[T,i,M,L]),U=((Ea=(Sa=(Na=E==null?void 0:E.metadata)==null?void 0:Na.executionResult)==null?void 0:Sa.error)==null?void 0:Ea.message)||((Pa=(ka=(Aa=m==null?void 0:m.status)==null?void 0:Aa.errors)==null?void 0:ka[0])==null?void 0:Pa.message);Xe({source:E?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:E==null?void 0:E.id,analysisId:m==null?void 0:m.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:E==null?void 0:E.name,errorMessage:U});const[W,$]=_(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ne(()=>{l&&l!==W&&l!=="edit"&&$(l)},[l]);const K=l==="edit",[G,z]=_(!1),[B,Z]=_(!1),[V,X]=_(null),[ue,he]=_(!1),[ye,be]=_(!1),[Se,we]=_(null),[ke,je]=_(null),[xe,Le]=_(0),{interactiveServerUrl:Pe,isStarting:Ne,isLoading:un,showIframe:de,iframeKey:Je,onIframeLoad:Ve}=dn({analysisId:m==null?void 0:m.id,scenarioId:E==null?void 0:E.id,scenarioName:E==null?void 0:E.name,projectSlug:p,enabled:K&&!!E,refreshTrigger:xe}),[sr,Mg]=_(!1),[Tg,jg]=_(""),[hn,Ot]=_(!1),[ha,or]=_(Date.now()),[Ko,ir]=_(!1),et=Ae(),xt=Ae(),Be=Ae(),Fe=rt(),Qo=S.jobs.some(re=>{var fe;return(d==null?void 0:d.sha)&&((fe=re.entityShas)==null?void 0:fe.includes(d.sha))||re.type==="analysis"&&re.commitSha===(C==null?void 0:C.sha)&&re.entityShas&&re.entityShas.length===0}),lr=L,ma=((_a=d==null?void 0:d.metadata)==null?void 0:_a.defaultWidth)||((Ma=m==null?void 0:m.metadata)==null?void 0:Ma.defaultWidth)||1440,Zo=Math.round(ma*(900/1440));et.state==="submitting"||et.state,ae(()=>{var re;return!!((re=E==null?void 0:E.metadata)!=null&&re.interactiveExamplePath)},[E]);const{isCompleted:pa}=ft(p,hn);ne(()=>{et.state==="idle"&&et.data&&(et.data.success?setTimeout(()=>{or(Date.now()),Fe.revalidate(),Ot(!1)},1500):et.data.error&&(Ot(!1),alert(`Recapture failed: ${et.data.error}`)))},[et.state,et.data,Fe]),ne(()=>{hn&&pa&&setTimeout(()=>{or(Date.now()),Fe.revalidate(),Ot(!1)},1500)},[hn,pa,Fe]),ne(()=>{xt.state==="idle"&&xt.data&&(xt.data.success?setTimeout(()=>{or(Date.now()),Fe.revalidate(),Ot(!1)},1500):xt.data.error&&(Ot(!1),alert(`Recapture failed: ${xt.data.error}`)))},[xt.state,xt.data,Fe]);const fa=()=>{d&&(y&&x&&x!==d.sha?(R(`/entity/${x}/scenarios`),setTimeout(()=>{Be.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Be.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ne(()=>{Be.state==="idle"&&Be.data&&(Be.data.success?Fe.revalidate():Be.data.error&&alert(`Analysis failed: ${Be.data.error}`))},[Be.state,Be.data,d==null?void 0:d.sha,Fe]),ne(()=>{const re=setTimeout(()=>{Fe.revalidate()},500);return()=>clearTimeout(re)},[]),ne(()=>{if(q||lr){const re=setInterval(()=>{Fe.revalidate()},3e3);return()=>clearInterval(re)}else{const re=setInterval(()=>{Fe.revalidate()},5e3),fe=setTimeout(()=>{clearInterval(re)},3e4);return()=>{clearInterval(re),clearTimeout(fe)}}},[q,lr,Fe]);const Xo=(re,fe)=>re==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${re}`,ei=(re,fe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${re}/${fe}`,ti=re=>{$(re),E!=null&&E.id&&(re==="interactive"?R(`/entity/${d==null?void 0:d.sha}/scenarios/${E.id}/fullscreen`,{replace:!0}):R(ei(E.id,re),{replace:!0}))},ni=async re=>{var fe,Ue;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:re,hasSelectedScenario:!!E,hasAnalysis:!!m}),!E||!m){const Ee="Error: No scenario or analysis available";console.error("[EntityDetail]",Ee),X(Ee);return}z(!0),X(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:re,scenarioId:E.id,scenarioName:E.name,currentData:E.data});try{const Ee=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:re,existingScenarios:m.scenarios,scenariosDataStructure:(fe=m.metadata)==null?void 0:fe.scenariosDataStructure,editingMockName:E.name,editingMockData:ke||((Ue=E.metadata)==null?void 0:Ue.data)})}),tt=await Ee.json();if(!Ee.ok||!tt.success)throw new Error(tt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",tt.data),je(tt.data);const mn=(m.scenarios||[]).map(ze=>ze.id===E.id?{...ze,metadata:{...ze.metadata,data:tt.data}}:ze),Yt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:mn})}),Ge=await Yt.json();if(!Yt.ok||!Ge.success)throw console.error("[EntityDetail] Temp save failed:",Ge),new Error(Ge.error||"Failed to apply preview");if(X("Generating preview. Capturing screenshot..."),Pe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:Pe});const ze=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:Pe,scenarioId:E.id,projectId:m.projectId,viewportWidth:1440})}),zt=await ze.json();!ze.ok||!zt.success?(console.error("[EntityDetail] Direct capture failed:",zt),X("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),X('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const ze=new FormData;ze.append("analysisId",m.id||""),ze.append("scenarioId",E.id||"");const zt=await fetch("/api/recapture-scenario",{method:"POST",body:ze}),dr=await zt.json();!zt.ok||!dr.success?(console.warn("[EntityDetail] Recapture failed:",dr.error),X("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",dr.jobId),X('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}Le(ze=>ze+1),Fe.revalidate()}catch(Ee){console.error("Error applying changes:",Ee),X(`Error: ${Ee instanceof Error?Ee.message:String(Ee)}`)}finally{z(!1)}},ri=async(re,fe)=>{var Ue;if(!E||!m){X("Error: No scenario or analysis available");return}Z(!0),X(null),console.log("[EntityDetail] Saving scenario to database",{description:re,saveAsNew:fe});try{const Ee=ke||((Ue=E.metadata)==null?void 0:Ue.data);let tt;if(fe){const Ge={...E,id:`${E.name}-${Date.now()}`,name:`${E.name} (Copy)`,metadata:{...E.metadata,data:Ee},description:re||E.description};tt=[...m.scenarios||[],Ge]}else tt=(m.scenarios||[]).map(Ge=>Ge.id===E.id?{...Ge,metadata:{...Ge.metadata,data:Ee},description:re||Ge.description}:Ge);const mn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:tt})}),Yt=await mn.json();if(!mn.ok||!Yt.success)throw new Error(Yt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),X(fe?"New scenario created successfully":"Scenario saved successfully"),je(null),Fe.revalidate()}catch(Ee){console.error("Error saving scenario:",Ee),X(`Error: ${Ee instanceof Error?Ee.message:String(Ee)}`)}finally{Z(!1)}},ai=()=>{console.log("[EntityDetail] Edit mock data clicked"),X("Mock data editor coming soon")},si=async()=>{var re;if(!(E!=null&&E.id)){we("Cannot delete scenario without ID");return}he(!0),we(null);try{const fe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:E.id,screenshotPaths:((re=E.metadata)==null?void 0:re.screenshotPaths)||[]})}),Ue=await fe.json();if(!fe.ok||!Ue.success)throw new Error(Ue.error||"Failed to delete scenario");R(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(fe){console.error("[EntityDetail] Error deleting scenario:",fe),we(fe instanceof Error?fe.message:"Failed to delete scenario"),be(!1)}finally{he(!1)}},cr=m&&d&&m.entitySha!==d.sha,oi=d?kp(d):!1;return n(Xn,{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:M.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(re=>n(se,{to:Xo(re.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${T===re.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:T===re.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[re.label,re.count!==void 0&&re.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${T===re.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:re.count})]})},re.id))})]})}),(y||cr&&!u||b&&oi)&&!L&&!Qo&&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:cr&&!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.":cr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),y&&x&&v?n(se,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:re=>{re.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:re=>{re.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:fa,disabled:Be.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:re=>{Be.state==="idle"&&(re.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:re=>{Be.state==="idle"&&(re.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[T==="scenarios"&&c(ce,{children:[K&&E?n(_p,{scenario:E,entitySha:(d==null?void 0:d.sha)||"",onApply:ni,onSave:ri,onEditMockData:ai,onDelete:si,isApplying:G,isSaving:B,saveMessage:V,showDeleteConfirm:ye,onShowDeleteConfirm:be,isDeleting:ue,deleteError:Se}):n(Pp,{scenarios:M,hiddenScenarios:j,analysis:m,selectedScenario:E,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:ha,activeTab:T,entityType:d==null?void 0:d.entityType,entity:d,queueState:S,processIsRunning:A,isEntityAnalyzing:L,areScenariosStale:I,viewMode:W,setViewMode:ti,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Tp,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):K&&E?n(er,{scenarioId:E.id||E.name,scenarioName:E.name,iframeUrl:Pe,isStarting:Ne,isLoading:un,showIframe:de,iframeKey:Je,onIframeLoad:Ve,projectSlug:p,defaultWidth:1440,defaultHeight:900}):c("div",{className:"flex flex-col flex-1 min-h-0",children:[E&&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:E.name}),c("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[ma," × ",Zo]})]}),c("div",{className:"flex items-center gap-2",children:[n(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${E.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),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(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${E.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(jo,{selectedScenario:E,analysis:m,entity:d,viewMode:W,cacheBuster:ha,hasScenarios:M.length>0,isAnalyzing:lr,projectSlug:p,hasAnApiKey:N,processIsRunning:A,queueState:S})]})]}),T==="related"&&n($p,{relatedEntities:f}),T==="data"&&n(Fp,{entity:d,analysis:m,scenarios:M,onAnalyze:fa}),T==="code"&&n(Up,{entity:d,entityCode:g}),T==="history"&&n(jp,{entity:d,history:w})]}),Ko&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>ir(!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:re=>re.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:()=>ir(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(ut,{projectSlug:p,onClose:()=>ir(!1)})})]})})]})})}),Gp=Object.freeze(Object.defineProperty({__proto__:null,default:Vp,loader:Jp,meta:Wp,shouldRevalidate:Hp},Symbol.toStringTag,{value:"Module"}));async function qp(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:s,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Re();const i=pe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=le.join(i,".codeyam","config.json"),d=JSON.parse(await me.readFile(l,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=Qn(h);try{await me.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Te(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await pt({shas:t});if(!g||g.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let y=r;if((!y||y.length===0)&&(y=[...new Set(g.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${y.length} unique files`)),!y||y.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${y.length} files...`);const x=await Yc(p,f,y);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await dt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const w=b.currentRun;if(w&&w.id&&w.archivedAt)return;w&&(w.analysesCompleted&&w.analysesCompleted>0||w.capturesCompleted&&w.capturesCompleted>0)&&qc(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:h,filePaths:y,entityShas:t,entityNames:g.map(b=>b.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Kp({request:e,context:t}){if(e.method!=="POST")return H({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return H({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(s)h=[s];else return H({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return H({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await pt({shas:h}),p=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await qp({entityShas:h,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}`),H({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),H({error:"Failed to start analysis",details:a.message},{status:500})}}const Qp=Object.freeze(Object.defineProperty({__proto__:null,action:Kp},Symbol.toStringTag,{value:"Module"}));function Zp(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 $o(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const s=t.getHours(),o=t.getMinutes(),i=s>=12?"pm":"am",l=s%12||12,d=o.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 qe(e,t=[],r=!1){var u,m;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 s=e.analyses[0];if(!(((u=s.status)==null?void 0:u.scenarios)&&s.status.scenarios.length>0&&s.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||s.entitySha!==e.sha)return"not-analyzed";const i=s.createdAt?new Date(s.createdAt).getTime():0,l=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],h=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&&h?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 Xp=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function ef({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await ln();return H({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),H({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const tf=$e(function(){const t=Ye(),r=t.entities,a=t.queueState;Xe({source:"simulations-page"});const[s,o]=_(""),[i,l]=_("visual"),d=ae(()=>{const y=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const w=v.scenarios.filter(C=>{var N;return!((N=C.metadata)!=null&&N.sameAsDefault)}).map(C=>{var O,P,A,T,F;const N=(P=(O=C.metadata)==null?void 0:O.screenshotPaths)==null?void 0:P[0],S=(A=C.metadata)==null?void 0:A.noScreenshotSaved,k=N&&!S,M=(F=(T=v.status)==null?void 0:T.scenarios)==null?void 0:F.find(q=>q.name===C.name),j=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt;let R;return k?R="completed":j?R="capturing":R="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:N||"",scenarioId:C.id,state:R}}).filter(C=>C.state==="completed"||C.state==="capturing");w.length>0&&y.push({entity:x,screenshots:w,createdAt:v.createdAt||""})}}),y.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),y},[r]),h=ae(()=>r.filter(y=>{var b,w;const x=(b=y.analyses)==null?void 0:b[0];return!((w=x==null?void 0:x.scenarios)==null?void 0:w.some(C=>{var N,S;return(S=(N=C.metadata)==null?void 0:N.screenshotPaths)==null?void 0:S[0]}))}),[r]),u=ae(()=>d.filter(({entity:y})=>{const x=!s||y.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||y.entityType===i;return x&&v}),[d,s,i]),m=ae(()=>h.filter(y=>{const x=!s||y.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||y.entityType===i;return x&&v}),[h,s,i]),p=oe(y=>{o(y.target.value)},[]),f=oe(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(ht,{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(rn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:s,onChange: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(nf,{entity:y,screenshots:x,queueJobs:(a==null?void 0:a.jobs)||[]},y.sha))})),!g&&(m.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):m.map(y=>n(rf,{entity:y},y.sha)))]})]})})});function nf({entity:e,screenshots:t,queueJobs:r}){var f,g,y;const a=It(),s=Ae(),[o,i]=_(!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`)},h=()=>{i(!0),s.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ne(()=>{s.state==="idle"&&o&&i(!1)},[s.state,o]);const u=qe(e,r),m=Zp(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(We,{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(se,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),c("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(ce,{children:o||s.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:h,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>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:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Oe,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(ra,{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 rf({entity:e}){const t=Ae(),[r,a]=_(!1),s=()=>{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:s,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(We,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(se,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:$o(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:s,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const af=Object.freeze(Object.defineProperty({__proto__:null,default:tf,loader:ef,meta:Xp},Symbol.toStringTag,{value:"Module"}));function sf({request:e,context:t}){const r=t.dbNotifier||_r;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(s){const o=new TextEncoder;s.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
227
|
+
|
|
228
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
229
|
+
|
|
230
|
+
`))}catch{l()}};r.on("change",d);const h=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
231
|
+
|
|
232
|
+
`))}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 of=Object.freeze(Object.defineProperty({__proto__:null,loader:sf},Symbol.toStringTag,{value:"Module"}));function lf(){return new Response(JSON.stringify({status:"ok",version:Qr,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const cf=Object.freeze(Object.defineProperty({__proto__:null,loader:lf},Symbol.toStringTag,{value:"Module"}));function oa(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const a=r[1],s=r[2],o={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);return i&&(o.paths=i[1].split(`
|
|
233
|
+
`).filter(l=>l.trim().startsWith("-")).map(l=>l.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean)),{frontmatter:o,body:s}}async function rr(e,t=""){const r=[];try{const a=await me.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){const i=await rr(le.join(e,s.name),o);r.push(...i)}else s.isFile()&&s.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function ia(e){const t=await rr(e),r=[];for(const a of t){const s=le.join(e,a);try{const o=await me.readFile(s,"utf-8"),{frontmatter:i,body:l}=oa(o);r.push({filePath:a,absolutePath:s,frontmatter:i,body:l})}catch{}}return r}function df(e,t){return!t.frontmatter.paths||t.frontmatter.paths.length===0?!1:t.frontmatter.paths.some(r=>Is(e,r,{matchBase:!0}))}const uf="codeyam-rule-state.json",Ar=1;function Ro(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return Un.createHash("sha256").update(t).digest("hex")}function Do(e){return le.join(e,".claude",uf)}async function Lo(e){const t=Do(e);try{const r=await me.readFile(t,"utf-8"),a=JSON.parse(r);return a.version!==Ar?(console.warn(`[ruleState] Unknown version ${a.version}, using empty state`),{version:Ar,rules:{}}):a}catch{return{version:Ar,rules:{}}}}async function Fo(e,t){const r=Do(e),a=le.dirname(r);await me.mkdir(a,{recursive:!0}),await me.writeFile(r,JSON.stringify(t,null,2)+`
|
|
234
|
+
`,"utf-8")}async function Oo(e,t){const r=await Lo(e),a=new Set(t.map(s=>s.filePath));for(const s of Object.keys(r.rules))a.has(s)||delete r.rules[s];for(const s of t){const o=await me.readFile(s.absolutePath,"utf-8"),i=Ro(o),l=r.rules[s.filePath];l?l.contentHash!==i&&(r.rules[s.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[s.filePath]={contentHash:i,reviewed:!1}}return await Fo(e,r),r}async function vs(e,t,r,a){const s=await Lo(e);if(r){const o=le.join(e,".claude","rules"),i=le.join(o,t),l=await me.readFile(i,"utf-8"),d=Ro(l);s.rules[t]?(s.rules[t].reviewed=!0,s.rules[t].contentHash=d):s.rules[t]={contentHash:d,reviewed:!0}}else s.rules[t]&&(s.rules[t].reviewed=!1);await Fo(e,s)}function Yo(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function zo(e,t=""){const r=[],a=await me.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;s.isDirectory()?r.push(...await zo(le.join(e,s.name),o)):s.name.endsWith(".md")&&r.push(o)}return r}function Bo(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
235
|
+
`).filter(a=>!(!a.startsWith("+")&&!a.startsWith("-")||a.startsWith("+++")||a.startsWith("---"))).map(a=>a.substring(1).trim());if(t.length===0)return!1;const r=/^(timestamp:\s*[\d\-T:.Z]+|category:\s*\w+)$/;return t.every(a=>r.test(a))}async function hf({request:e}){const t=pe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),a=r.searchParams.get("action"),s=le.join(t,".claude","rules");if(a==="recent-changes")return pf(t,s);if(a==="reviewed-status")return ff(t,s);if(a==="audit")return gf(t,s);if(a==="source-files")return yf(t);if(a==="rules-for-path"){const o=r.searchParams.get("path");return o?xf(s,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await rr(s),i=[];for(const l of o){const d=le.join(s,l);try{const h=await me.readFile(d,"utf-8"),u=await me.stat(d),{frontmatter:m,body:p}=oa(h);i.push({filePath:l,content:h,frontmatter:m,body:p,lastModified:u.mtime.toISOString()})}catch{}}return i.sort((l,d)=>new Date(d.lastModified).getTime()-new Date(l.lastModified).getTime()),Response.json({memories:i})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o)},{status:500})}}async function mf(e,t){const r=[];try{const a=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const s of a.split(`
|
|
236
|
+
`).filter(Boolean)){const o=s.substring(0,2);let i=s.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],d=o[1];let h=[i];if(i.endsWith("/")&&l==="?"){const u=le.join(e,i);try{h=(await zo(u)).map(p=>i+p)}catch{continue}}for(const u of h){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let p="modified";l==="A"||l==="?"?p="added":l==="D"||d==="D"?p="deleted":(l==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&l==="?"){const g=`${e}/${u}`;try{const y=await me.readFile(g,"utf-8");f=`diff --git a/${u} b/${u}
|
|
237
|
+
new file mode 100644
|
|
238
|
+
--- /dev/null
|
|
239
|
+
+++ b/${u}
|
|
240
|
+
@@ -0,0 +1,${y.split(`
|
|
241
|
+
`).length} @@
|
|
242
|
+
${y.split(`
|
|
243
|
+
`).map(x=>"+"+x).join(`
|
|
244
|
+
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
245
|
+
... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&Bo(f)||r.push({filePath:m,changeType:p,diff:f})}}}catch{}return r}async function pf(e,t){try{const{execSync:r}=await import("child_process"),a=[],s=await ia(t),o=await Oo(e,s),i={};for(const m of s)i[m.filePath]=Yo(o,m.filePath);const d=(await mf(e,r)).filter(m=>!i[m.filePath]);d.length>0&&a.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:d});const u=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
|
|
246
|
+
`).filter(Boolean).slice(0,20);for(const m of u){const[p,f,...g]=m.split("|"),y=g.join("|");if(!p||!f)continue;const x=r(`git diff-tree --no-commit-id --name-status -r ${p} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),v=[];for(const b of x.split(`
|
|
247
|
+
`).filter(Boolean)){const[w,C]=b.split(" ");if(!C||!C.startsWith(".claude/rules/"))continue;const N=C.replace(".claude/rules/","");let S="modified";if(w==="A"?S="added":w==="D"&&(S="deleted"),i[N])continue;let k="";try{k=r(`git show ${p} --format="" -- "${C}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),k.length>5e3&&(k=k.substring(0,5e3)+`
|
|
248
|
+
... (truncated)`)}catch{k="(diff not available)"}S==="modified"&&Bo(k)||v.push({filePath:N,changeType:S,diff:k})}v.length>0&&a.push({commitHash:p.substring(0,8),date:f,message:y,files:v})}return Response.json({changes:a,reviewedStatus:i})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function ff(e,t){try{const r=await ia(t),a=await Oo(e,r),s={};for(const o of r)s[o.filePath]=Yo(a,o.filePath);return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Uo(e){const t=[],r=[".ts",".tsx",".js",".jsx",".vue",".svelte"];async function a(s,o){try{const i=await me.readdir(s,{withFileTypes:!0});for(const l of i){const d=le.join(s,l.name),h=o?`${o}/${l.name}`:l.name;if(!(l.isDirectory()&&(l.name==="node_modules"||l.name===".git"||l.name==="dist"||l.name===".codeyam"||l.name===".claude"||l.name==="build"||l.name==="coverage"))){if(l.isDirectory())await a(d,h);else if(l.isFile()){const u=le.extname(l.name);r.includes(u)&&t.push(h)}}}}catch{}}return await a(e,""),t}async function gf(e,t){try{const r=await ia(t),a=await Uo(e),s=[];for(const o of a){const i=r.filter(l=>df(o,l));if(i.length>0){const l=i.reduce((d,h)=>d+h.body.length,0);s.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:l})}}return s.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:s,totalFilesWithCoverage:s.length,allSourceFiles:a})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function yf(e){try{const t=await Uo(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function xf(e,t){try{const r=await rr(e),a=[];for(const o of r){const i=le.join(e,o);try{const l=await me.readFile(i,"utf-8"),d=await me.stat(i),{frontmatter:h,body:u}=oa(l);h.paths&&h.paths.some(m=>Is(t,m,{matchBase:!0}))&&a.push({filePath:o,content:l,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const s=a.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:a,totalTextLength:s})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function bf({request:e}){const t=pe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=le.join(t,".claude","rules");try{const a=await e.json(),{action:s,filePath:o,content:i,lastModified:l}=a;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(s==="mark-reviewed")return await vs(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(s==="mark-unreviewed")return await vs(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=le.normalize(o);if(d.includes("..")||le.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=le.join(r,d);switch(s){case"create":case"update":return i?(await me.mkdir(le.dirname(h),{recursive:!0}),await me.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${s}d: ${o}`),Response.json({success:!0,message:`Memory ${s}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await me.unlink(h),console.log(`[API] Memory deleted: ${o}`);const u=le.dirname(h);try{(await me.readdir(u)).length===0&&u!==r&&await me.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(a){return console.error("[API] Error managing memory:",a),Response.json({error:"Failed to manage memory",details:a instanceof Error?a.message:String(a)},{status:500})}}const vf=Object.freeze(Object.defineProperty({__proto__:null,action:bf,loader:hf},Symbol.toStringTag,{value:"Module"}));async function wf({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await it()),!r)return H({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return H({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return H({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return H({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 H({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?H({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):H({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>jt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>jt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return H({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return H({error:"Unknown queryType"},{status:400})}async function Cf({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 it(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),H({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:s,...o}=a;if(console.log("[Queue API] Action:",s,"Params:",Object.keys(o)),s==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),H({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),H({status:"resumed"});if(s==="pause")return r.pause(),H({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?H({status:"removed",jobId:i}):H({error:"Job not found in queue"},{status:404}):H({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return H({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?H({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?H({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?H({status:"reordered",jobId:i,direction:l}):H({error:"Could not reorder job (not found or at boundary)"},{status:400})}return H({error:"Unknown action"},{status:400})}const Nf=Object.freeze(Object.defineProperty({__proto__:null,action:Cf,loader:wf},Symbol.toStringTag,{value:"Module"})),Sf=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Ef=$e(function(){return Ae(),n(Xn,{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(jo,{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})]})]})})}),Af=Object.freeze(Object.defineProperty({__proto__:null,default:Ef,meta:Sf},Symbol.toStringTag,{value:"Module"})),kf=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function Pf({request:e}){try{const t=await Gr();if(!t)return H({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=pe()||process.cwd(),a=await Kn(r),s=po(t.projectSlug);return H({config:t,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:s,error:null})}catch(t){return console.error("Failed to load config:",t),H({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function _f(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 Mf({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),s=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore");let d;if(r)try{d=JSON.parse(r)}catch{return H({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let h;if(a)try{h=JSON.parse(a)}catch{return H({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 m;if(h){const g=await Gr();g!=null&&g.webapps&&(m=g.webapps.map((y,x)=>{if(h[x]!==void 0){const v=_f(h[x]);return{...y,startCommand:v}}return y}))}if(!await ao({universalMocks:d,pathsToIgnore:u,webapps:m}))return H({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(s!==void 0||o!==void 0||i!==void 0){const g=pe()||process.cwd(),y=await Kn(g);f=s!==void 0&&s!==(y.GROQ_API_KEY||"")||o!==void 0&&o!==(y.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(y.OPENAI_API_KEY||""),await Bc(g,{...y,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return H({success:!0,error:null,requiresRestart:f})}catch(t){return console.log("[Settings Action] Failed to save config:",t),H({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function ws(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Cs({mock:e,onSave:t,onCancel:r}){const[a,s]=_(e.entityName),[o,i]=_(e.filePath),[l,d]=_(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:u=>s(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#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:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),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()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Tf(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const jf=$e(function(){var B,Z;const{config:t,secrets:r,versionInfo:a,error:s}=Ye(),o=xi(),i=Ae(),l=rt(),[d,h]=_("project-metadata");Xe({source:"settings-page"});const[u,m]=_((t==null?void 0:t.universalMocks)||[]),[p,f]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,y]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[x,v]=_((r==null?void 0:r.GROQ_API_KEY)||""),[b,w]=_((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,N]=_((r==null?void 0:r.OPENAI_API_KEY)||""),[S,k]=_(!1),[M,j]=_(!1),[R,O]=_(!1),[P,A]=_(!1),[T,F]=_(!1),[q,J]=_(!1),[D,Y]=_(null),[L,I]=_(!1),[E,U]=_({});ne(()=>{var V;if(t){m(t.universalMocks||[]);const X=(t.pathsToIgnore||[]).join(", ");f(X),y(X);const ue={};(V=t.webapps)==null||V.forEach((he,ye)=>{he.startCommand&&(ue[ye]=ws(he.startCommand))}),U(ue)}r&&(v(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),N(r.OPENAI_API_KEY||""))},[t,r]),ne(()=>{if(o!=null&&o.success){A(!0);const V=setTimeout(()=>A(!1),3e3);return()=>clearTimeout(V)}},[o]),ne(()=>{if(i.state==="idle"&&i.data&&!q){console.log("[Settings] Fetcher data:",i.data);const V=i.data;if(V.success){console.log("[Settings] Save successful, revalidating..."),A(!0),J(!0),(p!==g||V.requiresRestart)&&F(!0),l.revalidate();const X=setTimeout(()=>{A(!1),J(!1)},3e3);return()=>clearTimeout(X)}}},[i.state,i.data,q,l,p,g]);const W=V=>{V.preventDefault();const X=new FormData(V.currentTarget);X.set("universalMocks",JSON.stringify(u)),X.set("startCommands",JSON.stringify(E)),console.log("[Settings] Submitting form data:",{universalMocks:X.get("universalMocks"),startCommands:X.get("startCommands"),openAiApiKey:X.get("openAiApiKey")?"***":"(empty)"}),i.submit(X,{method:"post"})},$=V=>{m([...u,V]),I(!1)},K=(V,X)=>{const ue=[...u];ue[V]=X,m(ue),Y(null)},G=V=>{m(u.filter((X,ue)=>ue!==V))};if(s)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:s})})]});const z=[{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:z.map(V=>n("li",{children:n("button",{type:"button",onClick:()=>h(V.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===V.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:V.label})},V.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((V,X)=>{var ue;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:V.path==="."?"Root":V.path})]}),V.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:V.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:V.framework})]}),V.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:[V.startCommand.command," ",(ue=V.startCommand.args)==null?void 0:ue.join(" ")]})]})]})},X)})}):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:V=>v(V.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>k(!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:M?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:b,onChange:V=>w(V.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>j(!M),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:M?"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:R?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:V=>N(V.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:()=>O(!R),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:R?"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((V,X)=>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:V.path==="."?"Root":V.path}),n("div",{className:"text-sm text-gray-600",children:V.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${X}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${X}`,name:`startCommand-${X}`,value:E[X]||"",onChange:ue=>U({...E,[X]:ue.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"})]})]},X))}):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:V=>f(V.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:()=>I(!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((V,X)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:D===X?n(Cs,{mock:V,onSave:ue=>K(X,ue),onCancel:()=>Y(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:V.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:V.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:V.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(X),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:()=>G(X),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},X))}),u.length>0&&n("button",{type:"button",onClick:()=>I(!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((V,X)=>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:V.path==="."?"Root":V.path})]}),V.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:V.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:V.framework})]}),V.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:ws(V.startCommand)})]})]})},X))})]})]}),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||((B=a.templateVersion.gitCommit)==null?void 0:B.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",Tf(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||((Z=a.cachedAnalyzerVersion.gitCommit)==null?void 0:Z.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||T||(o==null?void 0:o.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!"}),T&&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"})]}),(o==null?void 0:o.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:o.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const V=i.data;return typeof V.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:V.error}):null}return null})()]}),L&&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(Cs,{mock:{entityName:"",filePath:"",content:""},onSave:$,onCancel:()=>I(!1)})]})})]})})}),If=Object.freeze(Object.defineProperty({__proto__:null,action:Mf,default:jf,loader:Pf,meta:kf},Symbol.toStringTag,{value:"Module"}));async function $f({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=pe();if(!r)return new Response("Project root not found",{status:500});const s=le.extname(t)!==""?t:`${t}.html`,o=le.join(r,".codeyam","captures","static",s);try{await me.access(o);let i=await me.readFile(o);const l=le.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const 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>`;h=h.replace(u[0],g)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"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 Rf=Object.freeze(Object.defineProperty({__proto__:null,loader:$f},Symbol.toStringTag,{value:"Module"}));function Df(e,t,r=10){var d;const a=new Map,s=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)s(h)&&a.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const g of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(g)}}const i=[],l=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),l.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const m=o.get(h);if(m)for(const p of m){if(l.has(p))continue;l.add(p);const f=t.find(g=>g.sha===p);if(f){if(s(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((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function On(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const s=a.sort((o,i)=>{var h,u;const l=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(s[0])}return r}function Wo(e,t){const r=new Map,a=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&a.add(s.oldPath);for(const s of e){const o=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),i=o.filter(d=>{var h,u;return a.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),l=On(i);r.set(s.path,{status:s,entities:o,editedEntities:l})}return r}function Lf(e,t,r){const a=new Map;if(!r){for(const o of e)if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),l=On(i);a.set(o.path,{status:o,entities:l})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&s.set(o.filePath,i)}for(const o of e){const i=s.get(o.path);if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=On(l);a.set(o.path,{status:o,entities:d})}}return a}function Ff(e,t){const r=new Map,a=Ho(e,t);for(const s of a){const i=Df([s],t).filter(({depth:l})=>l>0);r.set(s.sha,i)}return r}function Ho(e,t){const r=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&r.add(s.oldPath);const a=t.filter(s=>{var o,i;return r.has(s.filePath)&&((o=s.metadata)==null?void 0:o.isUncommitted)&&!((i=s.metadata)!=null&&i.isSuperseded)});return On(a)}function Of({recentSimulations:e}){const t=ae(()=>{const r=new Map;return e.forEach(a=>{const s=a.entitySha,o=r.get(s);o?o.push(a):r.set(s,[a])}),Array.from(r.entries()).map(([a,s])=>({entitySha:a,entityName:s[0].entityName,scenarios:s}))},[e]);return 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(Kt,{size:16,style:{color:"#8B5CF6"}})}),n(se,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((a,s)=>n(se,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:n(Oe,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${s}`))})]},r.entitySha))}),n(se,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):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(Kt,{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(se,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(se,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Yf="/assets/codeyam-name-logo-CvKwUgHo.svg",zf=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Bf({request:e,context:t}){var r,a,s,o;try{const i=await De();if(i){const{project:P}=await Te(i);if(!(((a=(r=P.metadata)==null?void 0:r.labs)==null?void 0:a.simulations)??!0))return bi("/memory")}const l=t.analysisQueue,d=l?l.getState():{paused:!1,jobs:[]},[h,u]=await Promise.all([ln(),Dt()]),m=Ao(),p=h?Wo(m,h):new Map,f=Array.from(p.entries()).sort((P,A)=>P[0].localeCompare(A[0])),g=(h==null?void 0:h.length)||0,y=(h==null?void 0:h.filter(P=>P.entityType==="visual").length)||0,x=(h==null?void 0:h.filter(P=>P.entityType==="library").length)||0,v=h?Ho(m,h):[],b=v.length,w=(h==null?void 0:h.filter(P=>(P.analyses??[]).filter(A=>A.scenarios&&A.scenarios.length>0).length>0).length)||0,C=(h==null?void 0:h.reduce((P,A)=>{var F,q,J;const T=((J=(q=(F=A.analyses)==null?void 0:F[0])==null?void 0:q.scenarios)==null?void 0:J.length)||0;return P+T},0))||0,N=(h==null?void 0:h.reduce((P,A)=>{var q,J;const F=(((J=(q=A.analyses)==null?void 0:q[0])==null?void 0:J.scenarios)||[]).filter(D=>{var Y,L;return(L=(Y=D.metadata)==null?void 0:Y.screenshotPaths)==null?void 0:L[0]}).length;return P+F},0))||0,S=[];h==null||h.forEach(P=>{var T;const A=(T=P.analyses)==null?void 0:T[0];A!=null&&A.scenarios&&A.scenarios.filter(q=>{var J;return!((J=q.metadata)!=null&&J.sameAsDefault)}).forEach(q=>{var D,Y;const J=(Y=(D=q.metadata)==null?void 0:D.screenshotPaths)==null?void 0:Y[0];J&&S.push({entitySha:P.sha,entityName:P.name,scenarioId:q.id,scenarioName:q.name,screenshotPath:J,createdAt:A.createdAt||""})})}),S.sort((P,A)=>new Date(A.createdAt).getTime()-new Date(P.createdAt).getTime());const k=S.slice(0,16),M=(h==null?void 0:h.filter(P=>P.entityType==="visual").filter(P=>{var F,q;const A=(F=P.analyses)==null?void 0:F[0];return!((q=A==null?void 0:A.scenarios)==null?void 0:q.some(J=>{var D,Y;return(Y=(D=J.metadata)==null?void 0:D.screenshotPaths)==null?void 0:Y[0]}))}).slice(0,8))||[],j=(s=u==null?void 0:u.metadata)==null?void 0:s.currentRun,R=((o=j==null?void 0:j.currentEntityShas)==null?void 0:o.length)||0,O=d.jobs.length||0;return H({stats:{totalEntities:g,visualEntities:y,libraryEntities:x,uncommittedEntities:b,entitiesWithAnalyses:w,totalScenarios:C,capturedScreenshots:N,currentlyAnalyzing:R,filesOnQueue:O},uncommittedFiles:f,uncommittedEntitiesList:v,recentSimulations:k,visualEntitiesForSimulation:M,projectSlug:i,queueState:d,currentCommit:u})}catch(i){return console.error("Failed to load dashboard data:",i),H({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 Uf=$e(function(){var Y,L;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=Ye(),h=Ae(),u=rt(),{showToast:m}=Ur();Xe({source:"dashboard"});const[p,f]=_(new Set),[g,y]=_(null),[x,v]=_(!1),[b,w]=_(!1),{lastLine:C,isCompleted:N}=ft(i,!!g),{simulatingEntity:S,scenarios:k,scenarioStatuses:M,allScenariosCaptured:j}=ae(()=>{var z,B;const I={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return I;const E=o==null?void 0:o.find(Z=>Z.sha===g);if(!E)return I;const U=(z=E.analyses)==null?void 0:z[0],W=(U==null?void 0:U.scenarios)||[],$=((B=U==null?void 0:U.status)==null?void 0:B.scenarios)||[],K=$.filter(Z=>Z.screenshotFinishedAt).length,G=W.length>0&&K===W.length;return{simulatingEntity:E,scenarios:W,scenarioStatuses:$,allScenariosCaptured:G}},[g,o]);ne(()=>{(N||j)&&y(null)},[N,j]);const R=(Y=d==null?void 0:d.metadata)==null?void 0:Y.currentRun,O=new Set((R==null?void 0:R.currentEntityShas)||[]),P=new Set(l.jobs.flatMap(I=>I.entityShas||[])),A=new Set(((L=l.currentlyExecuting)==null?void 0:L.entityShas)||[]),T=a.filter(I=>I.entityType==="visual"||I.entityType==="library"),F=T.filter(I=>!O.has(I.sha)&&!P.has(I.sha)&&!A.has(I.sha)),q=()=>{if(F.length===0){m("All entities are already queued or analyzing","info",3e3);return}const I=F.map(E=>E.sha);w(!0),m(`Starting analysis for ${F.length} entities...`,"info",3e3),h.submit({entityShas:I.join(",")},{method:"post",action:"/api/analyze"})};ne(()=>{if(h.state==="idle"&&h.data){const I=h.data;I.success?(console.log("[Analyze All] Success:",I.message),m(`Analysis started for ${I.entityCount} entities in ${I.fileCount} files. Watch the logs for progress.`,"success",6e3),w(!1)):I.error&&(console.error("[Analyze All] Error:",I.error),m(`Error: ${I.error}`,"error",8e3),w(!1))}},[h.state,h.data,m]);const J=I=>{f(E=>{const U=new Set(E);return U.has(I)?U.delete(I):U.add(I),U})},D=[{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:Yf,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,I=>I.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:D.map((I,E)=>n(se,{to:I.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 ${I.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:I.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:[I.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:I.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:`${I.color}15`},children:[I.iconType==="folder"&&n(zi,{size:20,style:{color:I.color}}),I.iconType==="check"&&n(Lr,{size:20,style:{color:I.color}}),I.iconType==="image"&&n(Kt,{size:20,style:{color:I.color}}),I.iconType==="code-xml"&&n(Bi,{size:20,style:{color:I.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:I.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:I.color},children:"View All →"})]})]})},E))}),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"})]}),T.length>0&&n("button",{onClick:q,disabled:h.state!=="idle"||b||F.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:I=>I.currentTarget.style.backgroundColor="#004560",onMouseLeave:I=>I.currentTarget.style.backgroundColor="#005C75",children:h.state!=="idle"||b?"Starting analysis...":F.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([I,E])=>{const U=p.has(I),W=E.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:()=>J(I),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:U?"▼":"▶"}),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:I}),c("span",{className:"text-xs text-gray-500",children:[W.length," entit",W.length!==1?"ies":"y"]})]})]})}),U&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:W.length>0?W.map($=>{const K=O.has($.sha),G=P.has($.sha)||A.has($.sha);return c(se,{to:`/entity/${$.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:z=>z.currentTarget.style.borderColor="#005C75",onMouseLeave:z=>z.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:$.entityType==="visual"?"#8B5CF615":$.entityType==="library"?"#6366F1":"#EC4899"},children:[$.entityType==="visual"&&n(Kt,{size:16,style:{color:"#8B5CF6"}}),$.entityType==="library"&&n(As,{size:16,className:"text-white"}),$.entityType==="other"&&n(Ui,{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:$.name}),$.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),$.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),$.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),$.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:$.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[K&&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..."]}),!K&&G&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!K&&!G&&n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),m(`Starting analysis for ${$.name}...`,"info",3e3),h.submit({entityShas:$.sha},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:z=>z.currentTarget.style.backgroundColor="#004560",onMouseLeave:z=>z.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},$.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},I)})}):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(Of,{recentSimulations:s}),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:s.length>0?`Latest ${s.length} captured screenshot${s.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(We,{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})]})]})}),j?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 (",k.length," scenario",k.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:()=>v(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):h.state!=="idle"?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..."})]}),k.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:k.slice(0,8).map((I,E)=>{var B,Z,V;const U=(B=S==null?void 0:S.analyses)==null?void 0:B[0],W=nr(I,U==null?void 0:U.status,void 0,g||void 0,void 0),$=(V=(Z=I.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:V[0],K=W.isCaptured,G=W.status==="capturing"||W.status==="starting",z=W.hasError;return K?n(se,{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(Oe,{screenshotPath:$,alt:I.name,title:I.name,className:"max-w-full max-h-full object-contain object-center"})},E):z?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:"⚠️"})},E):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${G?"Capturing":"Pending"} ${I.name}...`,children:n("span",{className:G?"animate-pulse":"text-gray-400",children:G?"⋯":"⏹️"})},E)})})]})]})]}),x&&i&&n(ut,{projectSlug:i,onClose:()=>v(!1)})]})})}),Wf=Object.freeze(Object.defineProperty({__proto__:null,default:Uf,loader:Bf,meta:zf},Symbol.toStringTag,{value:"Module"}));function Jo({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(bl,{remarkPlugins:[vl],components:{h1:({children:a})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:a}),h2:({children:a})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:a}),h3:({children:a})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:a}),p:({children:a})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:a}),ul:({children:a})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),ol:({children:a})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),li:({children:a})=>n("li",{className:"leading-relaxed",children:a}),code:({children:a,className:s})=>(s==null?void 0:s.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:a})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:a}),pre:({children:a})=>n(ce,{children:a}),strong:({children:a})=>n("strong",{className:"font-semibold text-gray-900",children:a}),blockquote:({children:a})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:a}),table:({children:a})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:a})}),thead:({children:a})=>n("thead",{className:"bg-gray-50",children:a}),th:({children:a})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:a}),td:({children:a})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:a}),a:({children:a,href:s})=>n("a",{href:s,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:a})},children:r})}function Vo(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const a=r.filePath.split("/");a.pop();let s=t,o="";for(const i of a)o=o?`${o}/${i}`:i,s.children.has(i)||s.children.set(i,{name:i,path:o,memories:[],children:new Map}),s=s.children.get(i);a.length===0?t.memories.push(r):s.memories.push(r)}return t}function Go(e){let t=e.memories.length;for(const r of e.children.values())t+=Go(r);return t}function ar(e,t){var a;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||t}function Gt(e){return Math.round(e/3.5)}function Hf(e){const t=new Date(e),a=new Date().getTime()-t.getTime(),s=Math.floor(a/(1e3*60*60*24));return s===0?"Today":s===1?"Yesterday":s<7?`${s} days ago`:t.toLocaleDateString()}function Jf({rule:e,onEdit:t,onDelete:r,onView:a,isReviewed:s,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:d,diff:h,isFadingOut:u,showLeftBorder:m}){const[p,f]=_(!1),[g,y]=_(!1),x=ae(()=>ar(e.body,e.filePath),[e.body,e.filePath]),v=Gt(e.body.length),b=p?"#3e3e3e":l?"#d97706":"#c7c7c7",w=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,C={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return c("div",{className:w,style:C,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>a?a(e):f(!p),children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),c("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&c(ce,{children:[e.frontmatter.paths.slice(0,2).map((N,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:N},S)),e.frontmatter.paths.length>2&&c("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),c("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d?n("span",{className:"text-xs text-gray-400",children:Hf(d)}):e.frontmatter.timestamp&&c("span",{className:"text-xs text-gray-400",children:["Updated"," ",new Date(e.frontmatter.timestamp).toLocaleDateString()]}),o&&n("button",{onClick:N=>{N.stopPropagation(),o(e.filePath,e.lastModified,s??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${s?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:s?"Mark as unreviewed":"Mark as reviewed",children:s&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&c("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[c("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&h&&c("button",{onClick:N=>{N.stopPropagation(),y(!g)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${g?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(kn,{className:"w-3 h-3"}),g?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&c("div",{className:"flex items-center gap-2",children:[c("button",{onClick:N=>{N.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Wi,{className:"w-3 h-3"}),"Edit"]}),c("button",{onClick:N=>{N.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(Hi,{className:"w-3 h-3"}),"Delete"]})]})]}),g&&h&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.split(`
|
|
249
|
+
`).map((N,S)=>{let k="";return N.startsWith("+")&&!N.startsWith("+++")?k="text-green-400":N.startsWith("-")&&!N.startsWith("---")?k="text-red-400":N.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:N},S)})}),c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),c("div",{className:"flex items-center gap-2",children:[c("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(Io,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((N,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:N},S))})]}),!g&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Jo,{content:e.body})})]})]})}function Vf(){return`---
|
|
250
|
+
paths:
|
|
251
|
+
- '**/*.ts'
|
|
252
|
+
timestamp: ${new Date().toISOString().split(".")[0]+"Z"}
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
## Title
|
|
256
|
+
|
|
257
|
+
Description here.
|
|
258
|
+
|
|
259
|
+
**Learned:** ${new Date().toISOString().split("T")[0]} from [context]
|
|
260
|
+
`}function Ns({rule:e,onSave:t,onCancel:r}){const[a,s]=_(e?`.claude/rules/${e.filePath}`:""),[o,i]=_((e==null?void 0:e.content)||Vf()),[l,d]=_(!!e),h=!e;return c("div",{className:"p-6",children:[c("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Ps,{className:"w-5 h-5"})})]}),h&&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(kn,{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:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!h)&&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/)"}),c("div",{className:"relative",children:[n("input",{type:"text",value:a,onChange:u=>s(u.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(a)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(qt,{className:"w-4 h-4"})})]})]}),e&&c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),c("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${a}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${a}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(qt,{className:"w-4 h-4"})})]})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:u=>i(u.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(a.replace(/^\.claude\/rules\//,""),o),disabled:!a.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Gf({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:a,onToggleFolder:s}){const o=ae(()=>Vo(e),[e]),i=(h,u,m)=>{if(h.target.closest(".chevron-toggle")){m&&s(u||"root");return}const f=u||null;r(t===f?null:f),m&&!a.has(u||"root")&&s(u||"root")},l=h=>{r(t===h?null:h)},d=(h,u=0)=>{const m=a.has(h.path||"root"),p=Go(h),f=h.children.size>0,g=h.name==="root"?"(root)":h.name,y=h.memories.length>0||f,x=h.path||"",v=t===x||t===null&&x==="";return c("div",{children:[c("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,h.path,y),children:[y&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),s(h.path||"root")},children:n($t,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!y&&n("div",{className:"w-3"}),n(_s,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:g}),c("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),m&&c("div",{className:"relative",children:[(h.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(b=>{var C;const w=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${w?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(b.filePath),children:n("span",{className:"text-xs",children:(C=b.filePath.split("/").pop())==null?void 0:C.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(h.children.values()).sort((b,w)=>b.name.localeCompare(w.name)).map(b=>d(b,u+1))})]})]},h.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function qf({memories:e,onEdit:t,onDelete:r,expandedFolders:a,onToggleFolder:s,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:d}){const[h,u]=_({});ne(()=>{u({})},[o]);const m=ae(()=>({...o,...h}),[o,h]),p=ae(()=>Vo(e),[e]),f=(y,x,v)=>{u(b=>({...b,[y]:!v})),v?l(y):i(y,x)},g=(y,x=0)=>{const v=a.has(y.path||"root"),b=y.children.size>0,w=y.name==="root"?"root":y.name,C=y.memories.length>0||b;return c("div",{children:[c("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>C&&s(y.path||"root"),children:[C&&n($t,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!C&&n("div",{className:"w-4"}),n(_s,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:w})]}),v&&c("div",{className:"ml-10 space-y-4 relative",children:[(y.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),y.memories.length>0&&n("div",{className:"space-y-2",children:y.memories.map(N=>n(Jf,{rule:N,onEdit:t,onDelete:r,onView:d,isReviewed:m[N.filePath]??!1,onToggleReviewed:f},N.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(y.children.values()).sort((N,S)=>N.name.localeCompare(S.name)).map(N=>g(N,x+1))})]})]},y.path||"root")};return n("div",{children:g(p)})}function Kf(e){const t=new Date(e),a=new Date().getTime()-t.getTime(),s=Math.floor(a/(1e3*60*60)),o=Math.floor(a/(1e3*60*60*24));return s<1?"Just now":s<24?`${s}h`:o===1?"Yesterday":o<7?`${o}d`:`${Math.floor(o/7)}w`}function Qf({changes:e,memories:t,reviewedStatus:r,onViewRule:a}){const[s,o]=_("unreviewed"),[i,l]=_(new Map),d=ve(r),h=ve([]);ne(()=>()=>{h.current.forEach(clearTimeout)},[]),ne(()=>{const p=d.current,f=[];for(const[g,y]of Object.entries(r))y&&!p[g]&&f.push(g);d.current=r,f.length!==0&&(l(g=>{const y=new Map(g);return f.forEach(x=>y.set(x,"approved")),y}),h.current.push(setTimeout(()=>{l(g=>{const y=new Map(g);return f.forEach(x=>y.set(x,"fading")),y})},1500)),h.current.push(setTimeout(()=>{l(g=>{const y=new Map(g);return f.forEach(x=>y.delete(x)),y})},2500)))},[r]);const u=ae(()=>{const p=new Map;for(const f of e){const g=f.commitHash==="uncommitted";for(const y of f.files){if(p.has(y.filePath))continue;const x=t.find(v=>v.filePath===y.filePath);x&&p.set(y.filePath,{rule:x,changeType:y.changeType,date:f.date,isUncommitted:g,diff:y.diff,isReviewed:r[y.filePath]??!1})}}return Array.from(p.values()).sort((f,g)=>f.isUncommitted&&!g.isUncommitted?-1:!f.isUncommitted&&g.isUncommitted?1:new Date(g.date).getTime()-new Date(f.date).getTime())},[e,t,r]),m=ae(()=>s==="unreviewed"?u.filter(p=>!p.isReviewed||i.has(p.rule.filePath)):u,[u,s,i]);return c("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"flex items-center gap-6 border-b border-[#e1e1e1] px-5",children:[n("h2",{className:"text-base leading-6 py-3 text-[#232323] whitespace-nowrap",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:`flex items-center gap-1.5 px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${s==="unreviewed"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#9ca3af"}}),n("span",{className:"text-sm leading-6",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400},children:"Unreviewed"})]}),c("button",{onClick:()=>o("all"),className:`flex items-center gap-1.5 px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${s==="all"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#9ca3af"}}),n("span",{className:"text-sm leading-6",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400},children:"All"})]})]}),c("div",{className:"grid grid-cols-[1fr_80px_70px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Changed"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center",children:"Reviewed"})]}),n("div",{className:"max-h-[400px] overflow-y-auto",children:m.slice(0,8).map(p=>{const{rule:f,changeType:g,date:y,isUncommitted:x}=p,v=p.isReviewed,b=i.get(f.filePath),w=ar(f.body,f.filePath);return n("div",{className:`border-b border-gray-50 transition-all ${b==="fading"?"duration-1000":"duration-300"}`,style:{opacity:b==="fading"?0:1},children:c("div",{className:`grid grid-cols-[1fr_80px_70px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${b==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>a(f,{changeType:g,date:y}),children:[c("div",{className:"flex items-center gap-2 min-w-0",children:[n("span",{className:"text-sm text-gray-900 truncate",children:w}),n("span",{className:`flex-shrink-0 px-1.5 py-0.5 rounded text-[10px] uppercase font-medium tracking-wider ${g==="added"?"bg-green-100 text-green-700":g==="modified"?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}`,children:g})]}),n("span",{className:"text-xs text-gray-500",children:x?"Uncommitted":Kf(y)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${v?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:v&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},f.filePath)})}),m.length===0&&s==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function Zf({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:a}){const[s,o]=_("unreviewed"),[i,l]=_(null),[d,h]=_(""),[u,m]=_(0),[p,f]=_(!1),[g,y]=_(null),x=ve(null),v=ve(null),[b,w]=_({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[C,N]=_(!0);ne(()=>{(async()=>{N(!0);try{const F=await(await fetch("/api/memory?action=audit")).json();w({topPaths:F.topPaths||[],totalFilesWithCoverage:F.totalFilesWithCoverage||0,allSourceFiles:F.allSourceFiles||[]})}catch(T){console.error("Failed to load audit data:",T)}finally{N(!1)}})()},[e]);const S=ae(()=>s==="all"?b.topPaths:b.topPaths.filter(A=>A.matchingRules.some(T=>!t[T.filePath])),[b.topPaths,s,t]);ae(()=>b.topPaths.filter(A=>A.matchingRules.some(T=>!t[T.filePath])).length,[b.topPaths,t]);const k=A=>A.split("/").pop()||A,M=ae(()=>{const A=new Map;for(const T of b.topPaths)A.set(T.filePath,T);return A},[b.topPaths]),j=ae(()=>{if(!d.trim())return[];const A=d.toLowerCase(),T=[],F=[];for(const q of b.allSourceFiles){const J=q.toLowerCase();if(!J.includes(A))continue;const D=M.get(q)||{filePath:q,matchingRules:[],totalTextLength:0};J.startsWith(A)?T.push(D):F.push(D)}return T.sort((q,J)=>q.filePath.localeCompare(J.filePath)),F.sort((q,J)=>q.filePath.localeCompare(J.filePath)),[...T,...F].slice(0,8)},[d,b.allSourceFiles,M]),R=oe(A=>{var T;y(A),l(A.filePath),h(A.filePath),f(!1),(T=x.current)==null||T.blur()},[]),O=oe(()=>{var A;h(""),y(null),l(null),(A=x.current)==null||A.focus()},[]),P=oe(A=>{var T;!p||j.length===0||(A.key==="ArrowDown"?(A.preventDefault(),m(F=>Math.min(F+1,j.length-1))):A.key==="ArrowUp"?(A.preventDefault(),m(F=>Math.max(F-1,0))):A.key==="Enter"?(A.preventDefault(),R(j[u])):A.key==="Escape"&&(f(!1),(T=x.current)==null||T.blur()))},[p,j,u,R]);return ne(()=>{m(0)},[j]),c("div",{className:"bg-white rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center gap-6 border-b border-[#e1e1e1] px-5",children:[n("h2",{className:"text-base leading-6 py-3 text-[#232323] whitespace-nowrap",style:{fontFamily:"Sora",fontWeight:600},children:"Rules Audit"}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:`flex items-center gap-1.5 px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${s==="unreviewed"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#9ca3af"}}),n("span",{className:"text-sm leading-6",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400},children:"Unreviewed"})]}),c("button",{onClick:()=>o("all"),className:`flex items-center gap-1.5 px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${s==="all"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#9ca3af"}}),n("span",{className:"text-sm leading-6",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400},children:"All"})]})]}),c("div",{className:"grid grid-cols-[1fr_100px_120px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-right",children:"Unrev / Rules"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-right",children:"Unrev / Tokens"})]}),c("div",{className:"relative px-5 py-2 border-b border-gray-100",children:[c("div",{className:"relative",children:[n(rn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:x,type:"text",value:d,onChange:A=>{h(A.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:P,placeholder:"Search for a file...",className:`w-full pl-8 ${d?"pr-8":"pr-3"} py-1.5 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:A=>{A.preventDefault(),O()},className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3.5 h-3.5",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})})]}),p&&j.length>0&&n("div",{ref:v,className:"absolute left-5 right-5 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-[240px] overflow-y-auto",children:j.map((A,T)=>c("div",{onMouseDown:F=>{F.preventDefault(),R(A)},onMouseEnter:()=>m(T),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${T===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Pn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:A.filePath,children:(()=>{const F=A.filePath.toLowerCase().indexOf(d.toLowerCase());if(F===-1)return A.filePath;const q=A.filePath.slice(0,F),J=A.filePath.slice(F,F+d.length),D=A.filePath.slice(F+d.length);return c(ce,{children:[q,n("span",{className:"font-semibold text-[#005C75]",children:J}),D]})})()}),c("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[A.matchingRules.length," rule",A.matchingRules.length!==1?"s":""]})]},A.filePath))})]}),C&&n("div",{className:"px-5 py-6",children:c("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!C&&(S.length>0||g)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(g?[g,...S.filter(T=>T.filePath!==g.filePath)].slice(0,8):S.slice(0,8)).map((A,T)=>{const F=A.matchingRules.length,q=A.matchingRules.filter(E=>!t[E.filePath]),J=q.length,D=q.reduce((E,U)=>E+U.bodyLength,0),Y=J>0,L=i===A.filePath,I=(g==null?void 0:g.filePath)===A.filePath;return c("div",{children:[c("div",{onClick:()=>l(L?null:A.filePath),className:`grid grid-cols-[1fr_100px_120px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${I?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[c("div",{className:"flex items-center gap-2 min-w-0",children:[L?n(ht,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n($t,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Pn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:A.filePath,children:I?A.filePath:k(A.filePath)})]}),c("span",{className:"text-sm text-right",children:[n("span",{className:Y?"font-semibold text-[#1A5276]":"text-gray-400",children:J}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:F})]}),c("span",{className:"text-sm text-right",children:[c("span",{className:Y?"font-semibold text-[#1A5276]":"text-gray-400",children:["~",Gt(D).toLocaleString()]}),n("span",{className:"text-gray-300",children:" / "}),c("span",{className:"text-gray-500",children:["~",Gt(A.totalTextLength).toLocaleString()]})]})]}),L&&n("div",{className:"bg-gray-50 border-b border-gray-100",children:A.matchingRules.map(E=>{const U=r.find($=>$.filePath===E.filePath),W=t[E.filePath]??!1;return c("div",{onClick:$=>{$.stopPropagation(),U&&a(U)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Fr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:U?ar(U.body,U.filePath):E.filePath}),c("span",{className:"text-xs text-gray-400 flex-shrink-0",children:["~",Gt(E.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${W?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:W&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},E.filePath)})})]},A.filePath)})}),!C&&S.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:s==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"})]})}function Xf(e){const t=new Date(e),a=new Date().getTime()-t.getTime(),s=Math.floor(a/(1e3*60*60)),o=Math.floor(a/(1e3*60*60*24));return s<1?"Just now":s<24?`${s}h ago`:o===1?"Yesterday":o<7?`${o}d ago`:`${Math.floor(o/7)}w ago`}function eg({rule:e,changeInfo:t,isReviewed:r,onApprove:a,onEdit:s,onDelete:o,onClose:i}){const l=ar(e.body,e.filePath),d=Gt(e.body.length);return ne(()=>{const h=u=>{u.key==="Escape"&&i()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:c("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:h=>h.stopPropagation(),children:[c("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[n("h2",{className:"text-lg font-semibold text-gray-900 truncate",children:l}),t&&c(ce,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:Xf(t.date)}),n("span",{className:`flex-shrink-0 px-2 py-0.5 rounded text-[10px] uppercase font-medium tracking-wider ${t.changeType==="added"?"bg-green-100 text-green-700":t.changeType==="modified"?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}`,children:t.changeType})]})]}),c("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[c("button",{onClick:a,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-[#005C75] text-white":"border border-[#005C75] text-[#005C75] hover:bg-[#f0f9ff]"}`,children:[n(nn,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:s,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 cursor-pointer transition-colors ml-1",children:n(Ps,{className:"w-5 h-5"})})]})]}),c("div",{className:"flex items-center gap-3 px-6 py-3 border-b border-gray-100",children:[c("span",{className:"text-xs text-gray-400 font-mono",children:[".claude/rules/",e.filePath]}),c("span",{className:"text-xs text-gray-400",children:["~",d.toLocaleString()," tokens"]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"px-6 py-3 border-b border-gray-100",children:[n("div",{className:"text-xs text-gray-500 mb-2 font-medium",children:"Applies to paths:"}),n("div",{className:"bg-gray-50 rounded-lg p-3 flex flex-wrap gap-2",children:e.frontmatter.paths.map((h,u)=>{const m=h.split("/"),p=m.pop()||h,f=m.length>0?m.join("/")+"/":"";return c("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-white rounded border border-gray-200 text-xs font-mono",children:[n(Pn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),f&&n("span",{className:"text-gray-400",children:f}),n("span",{className:"font-semibold text-gray-700",children:p})]},u)})})]}),n("div",{className:"px-6 py-4",children:n(Jo,{content:e.body})})]})})}const tg=()=>[{title:"CodeYam - Memory"},{name:"description",content:"Manage Claude Memory documentation"}];async function ng({request:e}){try{const[t,r]=await Promise.all([fetch(new URL("/api/memory",e.url).toString()),fetch(new URL("/api/memory?action=recent-changes",e.url).toString())]),a=await t.json(),s=await r.json();return a.error?H({memories:[],recentChanges:[],reviewedStatus:{},error:a.error}):H({memories:a.memories||[],recentChanges:s.changes||[],reviewedStatus:s.reviewedStatus||{},error:null})}catch(t){return console.error("Failed to load memories:",t),H({memories:[],recentChanges:[],reviewedStatus:{},error:"Failed to load memories"})}}const rg=$e(function(){const{memories:t,recentChanges:r,reviewedStatus:a,error:s}=Ye(),o=Ae(),i=rt(),[l,d]=_(""),[h,u]=_(null),[m,p]=_(new Set(["root"])),[f,g]=_(null),[y,x]=_(!1),[v,b]=_(null),[w,C]=_(0),[N,S]=_(null),[k,M]=_(null),[j,R]=_({}),O=$=>{p(K=>{const G=new Set(K);return G.has($)?G.delete($):G.add($),G})};Xe({source:"memory-page"});const P=ae(()=>({...a,...j}),[a,j]),A=ve(o.state);ne(()=>{const $=A.current==="loading"||A.current==="submitting",K=o.state==="idle";$&&K&&o.data&&(i.revalidate(),g(null),x(!1),C(G=>G+1)),A.current=o.state},[o.state,o.data,i]),ne(()=>{R($=>{const K={};for(const[G,z]of Object.entries($))a[G]!==z&&(K[G]=z);return Object.keys(K).length===Object.keys($).length?$:K})},[a]);const T=($,K)=>{R(G=>({...G,[$]:!0})),o.submit({action:"mark-reviewed",filePath:$,lastModified:K},{method:"POST",action:"/api/memory",encType:"application/json"})},F=$=>{R(K=>({...K,[$]:!1})),o.submit({action:"mark-unreviewed",filePath:$},{method:"POST",action:"/api/memory",encType:"application/json"})},q=($,K)=>{S($),M(K??null)},J=ae(()=>{let $=t;if(l.trim()){const K=l.toLowerCase();$=$.filter(G=>{var B;return(((B=G.filePath.split("/").pop())==null?void 0:B.replace(".md",""))||"").toLowerCase().includes(K)||G.body.toLowerCase().includes(K)})}return $},[t,l]),D=ae(()=>h?J.some(K=>K.filePath===h)?J.filter(K=>K.filePath===h):J.filter(K=>K.filePath.startsWith(h+"/")||K.filePath===h):J,[J,h]),Y=($,K)=>{const G=f?"update":"create";o.submit({action:G,filePath:$,content:K},{method:"POST",action:"/api/memory",encType:"application/json"})},L=$=>{o.submit({action:"delete",filePath:$.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},I=ae(()=>{const $=t.filter(K=>P[K.filePath]).length;return{total:t.length,reviewed:$,unreviewed:t.length-$,stale:0}},[t,P]),E=ae(()=>{const $=new Set(["root"]);for(const K of J){const G=K.filePath.split("/");G.pop();let z="";for(const B of G)z=z?`${z}/${B}`:B,$.add(z)}return $},[J]),U=E.size===m.size&&[...E].every($=>m.has($)),W=()=>{p(U?new Set(["root"]):new Set(E))};return s?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:s})]})}):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 mb-6",children:[c("div",{children:[c("div",{className:"flex items-center gap-3 mb-2",children:[n(ag,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),n("p",{className:"text-[15px] text-gray-500",children:"Rules help Claude understand your codebase patterns and conventions."})]}),c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative",children:[n(rn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:l,onChange:$=>d($.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),c("button",{onClick:()=>x(!0),className:"flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer font-mono uppercase text-xs font-semibold",children:[n(Fa,{className:"w-4 h-4"}),"New Rule"]})]})]}),c("div",{className:"grid grid-cols-4 gap-4",children:[n(Cn,{label:"Total Rules",count:I.total,icon:n(sg,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Cn,{label:"Unreviewed",count:I.unreviewed,icon:n(Ji,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Cn,{label:"Reviewed",count:I.reviewed,icon:n(nn,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Cn,{label:"Stale",count:I.stale,icon:n(ks,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]}),y&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>x(!1),children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:$=>$.stopPropagation(),children:n(Ns,{rule:null,onSave:Y,onCancel:()=>{x(!1)}})})}),f&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>g(null),children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:$=>$.stopPropagation(),children:n(Ns,{rule:f,onSave:Y,onCancel:()=>{g(null)}})})}),c("div",{className:"grid grid-cols-2 gap-8 mb-8",children:[n(Qf,{changes:r,memories:J,reviewedStatus:P,onViewRule:q}),n(Zf,{onEditRule:g,onDeleteRule:b,refreshKey:w,reviewedStatus:P,onMarkReviewed:T,onMarkUnreviewed:F,memories:t,onViewRule:q})]}),c("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:E.size>1&&n("button",{onClick:W,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:U?"Collapse All":"Expand All"})})]}),c("div",{className:"flex gap-6",children:[n("div",{className:"w-80 flex-shrink-0",children:n(Gf,{memories:J,selectedPath:h,onSelectPath:u,expandedFolders:m,onToggleFolder:O})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Vi,{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-memories"})," ","to generate initial memories for your codebase."]}),c("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Fa,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):c("div",{children:[h&&c("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:h||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(qf,{memories:D,onEdit:g,onDelete:b,expandedFolders:m,onToggleFolder:O,reviewedStatus:P,onMarkReviewed:T,onMarkUnreviewed:F,onViewRule:q})]})})]}),n("div",{className:"mt-8 mb-8",children:n(se,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:c("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),c("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),N&&!f&&(()=>{const $=t.find(K=>K.filePath===N.filePath)??N;return n(eg,{rule:$,changeInfo:k??void 0,isReviewed:P[$.filePath]??!1,onApprove:()=>{P[$.filePath]??!1?F($.filePath):T($.filePath,$.lastModified),S(null)},onEdit:()=>{g($)},onDelete:()=>{b($),S(null)},onClose:()=>S(null)})})(),v&&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 Memory?"}),c("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:v.filePath}),"? This cannot be undone."]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:()=>b(null),className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>L(v),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})]})})});function ag(){return c("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function Cn({label:e,count:t,icon:r,bgColor:a,iconBgColor:s,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:a,border:"1px solid #EFEFEF"},children:c("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:s},children:r}),c("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function sg(){return c("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}const og=Object.freeze(Object.defineProperty({__proto__:null,default:rg,loader:ng,meta:tg},Symbol.toStringTag,{value:"Module"}));function kr(e){return`${e.filePath||""}::${e.name}`}function qo(e,t){const r=Ae(),{showToast:a}=Ur(),[s,o]=_(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(s.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=>{s.forEach((v,b)=>{v===x&&p.add(b)})})}),e==null||e.forEach(g=>{s.forEach((y,x)=>{y===g&&p.add(x)})}),p.size>0&&o(g=>{const y=new Map(g);return p.forEach(x=>y.delete(x)),y})},[t,e,s]);const i=oe(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=kr(p);o(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=oe(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(kr(b),b.sha)),v});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=oe(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=oe(p=>{const f=kr(p);return s.has(f)},[s]),u=oe(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]),m=ae(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function la({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:s=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children: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:"STATE"})}),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:s,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:s?o:"Analyze all entities",children:o})})]})]})]})})}function ig({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},a={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const s=r[e]||{label:"?",bgColor:"bg-gray-500"};return 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 ${s.bgColor}`,title:e,children:s.label}),s.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function ca({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:l,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!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 ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[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(Fs,{filePath:e}),a&&n(ig,{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:s}),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:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:$o(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 da({entities:e,maxPreviews:t=3}){var a,s,o,i,l;const r=[];for(const d of e){if(r.length>=t)break;const h=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((l=u.metadata)!=null&&l.error);m&&r.push({type:"screenshot",screenshot:m,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,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return c(se,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(Oe,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(An,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(To,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function ua({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,m;const s=t||r?[{entityShas:[e.sha]}]:[],o=qe(e,s,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.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(se,{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(We,{type:"type"})})}):n(We,{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(na,{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?o==="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"]}):o==="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..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick: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"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.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(se,{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:v=>v.stopPropagation(),children:n(Oe,{screenshotPath:g,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function lg({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[x,v]=tn(),[b,w]=_(new Set),[C,N]=_(""),[S,k]=_(!1),[M,j]=_("all"),[R,O]=_("desc"),P=o||"all",A=ae(()=>{let E=e;return P!=="all"&&(E=E.filter(U=>U.entityType===P)),s==="analyzed"&&(E=E.filter(U=>U.analyses&&U.analyses.length>0)),E},[e,P,s]),T=ae(()=>{const E=new Map,U=new Map,W=new Map;A.forEach(z=>{var V,X;const B=`${z.filePath}::${z.name}`,Z=U.get(B);if(!Z)U.set(B,z),W.set(B,[]);else{const ue=((V=Z.metadata)==null?void 0:V.editedAt)||Z.createdAt||"",he=((X=z.metadata)==null?void 0:X.editedAt)||z.createdAt||"";let ye=!1;if(he>ue)ye=!0;else if(he===ue){const be=Z.createdAt||"";ye=(z.createdAt||"")>be}ye?(W.get(B).push(Z),U.set(B,z)):W.get(B).push(z)}}),U.forEach((z,B)=>{var V;if(!(z.analyses&&z.analyses.length>0)&&((V=z.metadata)!=null&&V.previousVersionWithAnalyses)){const ue=(W.get(B)||[]).find(he=>{var ye;return he.sha===((ye=z.metadata)==null?void 0:ye.previousVersionWithAnalyses)});ue&&ue.analyses&&ue.analyses.length>0&&(z.analyses=ue.analyses)}}),Array.from(U.values()).sort((z,B)=>{var X,ue,he,ye;const Z=!((X=z.metadata)!=null&&X.notExported)&&!((ue=z.metadata)!=null&&ue.namedExport),V=!((he=B.metadata)!=null&&he.notExported)&&!((ye=B.metadata)!=null&&ye.namedExport);return Z&&!V?-1:!Z&&V?1:0}).forEach(z=>{var ue,he,ye,be,Se;const B=z.filePath??"No File Path";E.has(B)||E.set(B,{filePath:B,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const Z=E.get(B);Z.entities.push(z),Z.totalCount++,(ue=z.metadata)!=null&&ue.isUncommitted&&Z.uncommittedCount++;const V=((be=(ye=(he=z.analyses)==null?void 0:he[0])==null?void 0:ye.scenarios)==null?void 0:be.length)||0;Z.simulationCount+=V;const X=((Se=z.metadata)==null?void 0:Se.editedAt)||z.updatedAt;X&&(!Z.lastUpdated||new Date(X)>new Date(Z.lastUpdated))&&(Z.lastUpdated=X)});const $=(i==null?void 0:i.jobs)||[],K=z=>{const B=`${z.filePath||""}::${z.name}`;return(d==null?void 0:d.includes(B))||!1};E.forEach(z=>{const B=z.entities.map(Z=>K(Z)?"queued":qe(Z,$));B.includes("analyzing")||B.includes("queued")?z.state="analyzing":B.includes("incomplete")?z.state="incomplete":B.includes("out-of-date")?z.state="out-of-date":B.includes("not-analyzed")?z.state="not-analyzed":z.state="up-to-date"}),E.forEach(z=>{var B,Z,V,X,ue;for(const he of z.entities){if(z.previewScreenshots.length+z.previewLibraryScenarios.length>=3)break;const be=((Z=(B=he.analyses)==null?void 0:B[0])==null?void 0:Z.scenarios)||[];if(he.entityType==="library"){const Se=be.find(we=>{var ke,je;return((ke=we.metadata)==null?void 0:ke.executionResult)||((je=we.metadata)==null?void 0:je.error)});Se&&z.previewLibraryScenarios.push({scenario:Se,entitySha:he.sha})}else{const Se=be.find(we=>{var ke,je;return(je=(ke=we.metadata)==null?void 0:ke.screenshotPaths)==null?void 0:je[0]});if(Se){const we=(X=(V=Se.metadata)==null?void 0:V.screenshotPaths)==null?void 0:X[0],ke=!!((ue=Se.metadata)!=null&&ue.error);we&&!z.previewScreenshots.includes(we)&&(z.previewScreenshots.push(we),z.previewScreenshotErrors.push(ke))}}}});const G=Array.from(E.values());return G.sort((z,B)=>{if(s==="analyzed"){const X=Math.max(...z.entities.filter(he=>{var ye,be;return(be=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:be.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0),ue=Math.max(...B.entities.filter(he=>{var ye,be;return(be=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:be.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0);return R==="desc"?ue-X:X-ue}if(z.uncommittedCount>0&&B.uncommittedCount===0)return-1;if(z.uncommittedCount===0&&B.uncommittedCount>0)return 1;const Z=z.lastUpdated?new Date(z.lastUpdated).getTime():0,V=B.lastUpdated?new Date(B.lastUpdated).getTime():0;return R==="desc"?V-Z:Z-V}),G},[A,s,R,i,d]),F=ae(()=>{let E=T;if(M!=="all"&&(E=E.filter(U=>U.state===M)),C.trim()){const U=C.toLowerCase();E=E.filter(W=>W.filePath.toLowerCase().includes(U))}return E},[T,C,M]),q=(t-1)*r,J=q+r,D=F.slice(q,J),Y=Math.ceil(F.length/r),L=E=>{w(U=>{const W=new Set(U);return W.has(E)?W.delete(E):W.add(E),W})},I=()=>{O(E=>E==="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:E=>{const U=E.target.value,W=new URLSearchParams(x);U==="all"?W.delete("entityType"):W.set("entityType",U),W.set("page","1"),v(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(ht,{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:M,onChange:E=>j(E.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(ht,{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(rn,{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:E=>N(E.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==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:F.length})," ",F.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:F.reduce((E,U)=>E+U.totalCount,0)})," ",F.reduce((E,U)=>E+U.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:[F.filter(E=>E.uncommittedCount>0).length," ","uncommitted"," ",F.filter(E=>E.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):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"]})]}),D.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:()=>{w(new Set(D.map(E=>E.filePath))),k(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ms,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:()=>{w(new Set),k(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ts,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(la,{showActions:!0,sortOrder:R,onSortChange:I}),n("div",{className:"flex flex-col gap-[3px]",children:D.map(E=>{const U=b.has(E.filePath),$=E.entities.filter(B=>(B.entityType==="visual"||B.entityType==="library")&&(qe(B,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(B,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(B,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,K=B=>{var Z;return((Z=a==null?void 0:a.currentEntityShas)==null?void 0:Z.includes(B))||!1},G=B=>{var Z;return l!=null&&l(B)?!0:((Z=i==null?void 0:i.jobs)==null?void 0:Z.some(V=>{var X;return(X=V.entityShas)==null?void 0:X.includes(B.sha)}))||!1},z=B=>{h==null||h(B)};return n(ca,{filePath:E.filePath,isExpanded:U,onToggle:()=>L(E.filePath),simulationPreviews:n(da,{entities:E.entities,maxPreviews:1}),entityCount:E.totalCount,state:E.state,lastModified:E.lastUpdated,uncommittedCount:E.uncommittedCount,isUncommitted:E.uncommittedCount>0,actionButton:$?n("button",{onClick:B=>{B.stopPropagation();const Z=E.entities.filter(V=>(V.entityType==="visual"||V.entityType==="library")&&(qe(V,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(V,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(V,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(Z)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:E.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:E.entities.sort((B,Z)=>{var ye,be,Se,we;const V=!((ye=B.metadata)!=null&&ye.notExported)&&!((be=B.metadata)!=null&&be.namedExport),X=!((Se=Z.metadata)!=null&&Se.notExported)&&!((we=Z.metadata)!=null&&we.namedExport);if(V&&!X)return-1;if(!V&&X)return 1;const ue=B.entityType==="visual"||B.entityType==="library",he=Z.entityType==="visual"||Z.entityType==="library";return ue&&!he?-1:!ue&&he?1:B.name.localeCompare(Z.name)}).map(B=>n(ua,{entity:B,isActivelyAnalyzing:K(B.sha),isQueued:G(B),onGenerateSimulation:z},B.sha))},E.filePath)})}),Y>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 ",Y]}),t<Y&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const cg=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function dg({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),s=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([ln(),Dt()]);return H({entities:d,currentCommit:h,page:a,filter:s,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),H({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const ug=$e(function(){var C,N,S;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i,error:l}=Ye();rt();const[d,h]=tn(),[u,m]=_(!1);Xe({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:g,pendingEntityKeys:y}=qo((N=(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun)==null?void 0:N.currentEntityShas,i),x=t||[],v=ae(()=>{const k=new Set([]);for(const M of x)k.add(M.filePath??"No File Path");return Array.from(k)},[x]),b=ae(()=>{let k=x;return u&&(k=k.filter(M=>{var j;return(j=M.metadata)==null?void 0:j.isUncommitted})),k.sort((M,j)=>{var R,O,P,A,T,F;return(R=M.metadata)!=null&&R.isUncommitted&&!((O=j.metadata)!=null&&O.isUncommitted)?-1:!((P=M.metadata)!=null&&P.isUncommitted)&&((A=j.metadata)!=null&&A.isUncommitted)?1:new Date(((T=j.metadata)==null?void 0:T.editedAt)||0).getTime()-new Date(((F=M.metadata)==null?void 0:F.editedAt)||0).getTime()})},[x,u]),w=ae(()=>{var M;const k=new Set([]);for(const j of x)(M=j.metadata)!=null&&M.isUncommitted&&k.add(j.filePath??"No File Path");return Array.from(k)},[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(lg,{entities:b,page:a,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:g,pendingEntityKeys:y,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:w.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),hg=Object.freeze(Object.defineProperty({__proto__:null,default:ug,loader:dg,meta:cg},Symbol.toStringTag,{value:"Module"})),mg=()=>[{title:"CodeYam - Labs"},{name:"description",content:"Experimental features"}];async function pg({request:e}){var t;try{const r=await De();if(!r)return H({labs:null,error:"Project not found"});const{project:a}=await Te(r);return H({labs:((t=a.metadata)==null?void 0:t.labs)??null,error:null})}catch(r){return console.error("Failed to load labs config:",r),H({labs:null,error:"Failed to load labs configuration"})}}async function fg({request:e}){try{const t=await e.formData(),r=t.get("feature"),a=t.get("enabled")==="true";if(!r)return H({success:!1,error:"Missing feature name"},{status:400});const s=await De();return s?(await qs({projectSlug:s,metadataUpdate:{labs:{[r]:a}}}),H({success:!0,error:null})):H({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),H({success:!1,error:"Failed to save labs configuration"},{status:500})}}const gg=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible."}],yg=$e(function(){const{labs:t,error:r}=Ye(),a=Ae();return Xe({source:"labs-page"}),r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:r})})]})}):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",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("p",{className:"text-[15px] text-gray-500",children:"Opt in to experimental features. These features may change or be removed at any time."})]}),n("div",{className:"space-y-4",children:gg.map(s=>{var l;const o=(t==null?void 0:t[s.id])??!0,i=a.state==="submitting"&&((l=a.formData)==null?void 0:l.get("feature"))===s.id;return c("div",{className:"border border-gray-200 rounded-lg p-6 bg-white",children:[c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1 mr-6",children:[n("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:s.name}),n("p",{className:"text-sm text-gray-600",children:s.description})]}),c(a.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:s.id}),n("input",{type:"hidden",name:"enabled",value:String(!o)}),n("button",{type:"submit",disabled:i,className:`relative inline-flex h-7 w-12 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${o?"bg-[#005C75]":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-6 w-6 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${o?"translate-x-5":"translate-x-0"}`})})]})]}),n("div",{className:"mt-3",children:n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${o?"bg-emerald-100 text-emerald-800":"bg-gray-100 text-gray-600"}`,children:o?"Enabled":"Disabled"})})]},s.id)})})]})})}),xg=Object.freeze(Object.defineProperty({__proto__:null,action:fg,default:yg,loader:pg,meta:mg},Symbol.toStringTag,{value:"Module"}));function bg(e,t,r){const[a,s]=_(()=>new Set),[o,i]=_(()=>new Set),l=ve([]),d=ve([]);return ne(()=>{(t.length!==l.current.length||t.some((y,x)=>y!==l.current[x]))&&(l.current=t,s(y=>{const x=new Set;return t.forEach(v=>{y.has(v)&&x.add(v)}),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(v=>{y.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,x)=>{x(v=>{const b=new Set(v);return b.has(g)?b.delete(g):b.add(g),b})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function vg(e,t,r){const[a,s]=_(null),[o,i]=_(null),l=Ae();ne(()=>{var m,p;((m=l.data)==null?void 0:m.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=m=>{s({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},h=(m,p)=>{s({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function wg({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var h;const[o,i]=_(!1),[l,d]=_(!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:"," ",((h=a.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(wl,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:s,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function Cg({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=e.flatMap(([w,{entities:C}])=>{const N=C.filter(S=>i(S.sha)||l(S)).map(S=>S.sha);return N.length>0?[{entityShas:N}]:[]}),v=w=>{const C=w.map(N=>qe(N,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"},b=ae(()=>[...e].sort((w,C)=>{const N=w[1].entities.reduce((j,R)=>{var P;const O=((P=R.metadata)==null?void 0:P.editedAt)||R.updatedAt;return O?j?new Date(O)>new Date(j)?O:j:O:j},null),S=C[1].entities.reduce((j,R)=>{var P;const O=((P=R.metadata)==null?void 0:P.editedAt)||R.updatedAt;return O?j?new Date(O)>new Date(j)?O:j:O:j},null);if(!N&&!S)return 0;if(!N)return 1;if(!S)return-1;const k=new Date(N).getTime(),M=new Date(S).getTime();return d==="desc"?M-k:k-M}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(la,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:C,entities:N,isUncommitted:S}])=>{const k=o.has(w),M=v(N),j=N.reduce((A,T)=>{var q;const F=((q=T.metadata)==null?void 0:q.editedAt)||T.updatedAt;return F?A?new Date(F)>new Date(A)?F:A:F:A},null),O=N.filter(A=>A.entityType==="visual"||A.entityType==="library").length===0;let P;return O?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="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..."]}):M==="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"}):M==="out-of-date"?P=n("button",{onClick:A=>{A.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!l(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(P=n("button",{onClick:A=>{A.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!l(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ca,{filePath:w,isExpanded:k,onToggle:()=>h(w),fileStatus:C,isUncommitted:S,simulationPreviews:n(da,{entities:N,maxPreviews:1}),entityCount:N.length,state:M,lastModified:j,isNotAnalyzable:O,actionButton:P,children:N.sort((A,T)=>{const F=A.entityType==="visual"||A.entityType==="library",q=T.entityType==="visual"||T.entityType==="library";return F&&!q?-1:!F&&q?1:0}).map(A=>n(ua,{entity:A,isActivelyAnalyzing:i(A.sha),isQueued:l(A),onGenerateSimulation:m},A.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 Ng({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=ae(()=>{const w=[];return e.forEach(([C,{editedEntities:N}])=>{const S=N.filter(k=>a(k.sha)||s(k)).map(k=>k.sha);S.length>0&&w.push({entityShas:S})}),w},[e,a,s]),v=ae(()=>{const w=new Map;return e.forEach(([C,{editedEntities:N}])=>{const S=N.map(R=>qe(R,x));let k;S.includes("analyzing")||S.includes("queued")?k="analyzing":S.includes("out-of-date")?k="out-of-date":S.includes("not-analyzed")?k="not-analyzed":k="up-to-date";const M=N.reduce((R,O)=>{var A;const P=((A=O.metadata)==null?void 0:A.editedAt)||O.updatedAt;return P&&(!R||new Date(P)>new Date(R))?P:R},null),j=N.filter(R=>R.entityType==="visual"||R.entityType==="library").length;w.set(C,{state:k,lastModified:M,analyzableCount:j})}),w},[e,x]),b=ae(()=>[...e].sort((w,C)=>{const N=v.get(w[0]),S=v.get(C[0]),k=N==null?void 0:N.lastModified,M=S==null?void 0:S.lastModified;if(!k&&!M)return 0;if(!k)return 1;if(!M)return-1;const j=new Date(k).getTime(),R=new Date(M).getTime();return d==="desc"?R-j:j-R}),[e,v,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(la,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:C,editedEntities:N}])=>{const S=r.has(w),k=v.get(w),{state:M,lastModified:j,analyzableCount:R}=k,O=R===0;let P;return O?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="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..."]}):M==="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"}):M==="out-of-date"?P=n("button",{onClick:A=>{A.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(P=n("button",{onClick:A=>{A.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ca,{filePath:w,isExpanded:S,onToggle:()=>h(w),fileStatus:C,simulationPreviews:n(da,{entities:N,maxPreviews:1}),entityCount:N.length,state:M,lastModified:j,isNotAnalyzable:O,isUncommitted:!0,actionButton:P,children:N.sort((A,T)=>{const F=A.entityType==="visual"||A.entityType==="library",q=T.entityType==="visual"||T.entityType==="library";return F&&!q?-1:!F&&q?1:0}).map(A=>n(ua,{entity:A,isActivelyAnalyzing:a(A.sha),isQueued:s(A),onGenerateSimulation:m},A.sha))},w)})})]})}function Sg({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 Eg=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Ag({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),s=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return s==="branch"?d=Nn(a,o,i):d=$h(a),H({...d,entitySha:l})}return H({error:"Unknown action"},{status:400})}async function kg({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),s=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,d,h]=await Promise.all([ln(),Dt(),De()]),u=Ao(),m=_h(),p=Mh(),f=Th(),g=s||m,y=a||p;let x=[];return g&&g!==y&&(x=ko(y,g)),H({entities:l||[],gitStatus:u,currentBranch:g,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:y,branchDiff:x,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),H({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 Pg=$e(function(){var Ne,un;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=Ye();Xe({source:"git-page"});const[p,f]=tn(),[g,y]=_(null),[x,v]=_("desc"),[b,w]=_("branch"),C=p.get("expanded")==="true",N=()=>{v(de=>de==="desc"?"asc":"desc")},S=Ae(),k=S.data;ne(()=>{a&&l&&a!==l&&S.state==="idle"&&!k&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(a)}`)},[a,l,S,k]);const M=ae(()=>{const de=Wo(r,t);return Array.from(de.entries()).sort((Je,Ve)=>Je[0].localeCompare(Ve[0]))},[r,t]),j=ae(()=>{const de=Lf(d,t,k);return Array.from(de.entries()).sort((Je,Ve)=>Je[0].localeCompare(Ve[0]))},[d,t,k]),R=ae(()=>Ff(r,t),[r,t]),O=ae(()=>b==="uncommitted"?M:j,[b,M,j]),P=ae(()=>O.map(([de])=>de),[O]),{expandedUncommitted:A,setExpandedUncommitted:T,toggleFile:F,expandAllUncommitted:q,collapseAllUncommitted:J}=bg(C,P,[]),{diffView:D,diffContent:Y,isLoading:L,handleShowFileDiff:I,handleCloseDiff:E}=vg(l,a),U=(Ne=h==null?void 0:h.metadata)==null?void 0:Ne.currentRun,W=new Set((U==null?void 0:U.currentEntityShas)||[]),$=new Set(m.jobs.flatMap(de=>de.entityShas||[])),K=new Set(((un=m.currentlyExecuting)==null?void 0:un.entityShas)||[]),{isAnalyzing:G,handleGenerateSimulation:z,handleGenerateAllSimulations:B,isEntityBeingAnalyzed:Z,isEntityPending:V}=qo(U==null?void 0:U.currentEntityShas,m),X=de=>V(de)||$.has(de.sha)||K.has(de.sha),ue=de=>{de===(s||a)?p.delete("viewBranch"):p.set("viewBranch",de),f(p)},he=de=>{de===o?p.delete("compare"):p.set("compare",de),f(p)},ye=()=>{const Je=O.flatMap(([Ve,sr])=>sr.editedEntities||sr.entities||[]).filter(Ve=>!W.has(Ve.sha)&&!$.has(Ve.sha)&&!K.has(Ve.sha)&&!V(Ve));B(Je)},be=M.length,Se=j.length,we=O.flatMap(([de,Je])=>Je.editedEntities||Je.entities||[]),ke=we.filter(de=>de.entityType==="visual"||de.entityType==="library"),je=ke.length>0&&ke.every(de=>W.has(de.sha)),xe=ke.length>0&&!je&&ke.every(de=>$.has(de.sha)||K.has(de.sha)),Le=G||je||xe,Pe=je?"Analyzing...":xe?"Queued...":G?"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(Sg,{activeTab:b,onTabChange:w,uncommittedCount:be,branchCount:Se})}),a&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===o?c("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):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:de=>ue(de.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(de=>n("option",{value:de,children:de},de))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),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:de=>he(de.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(de=>de!==a).map(de=>n("option",{value:de,children:de},de))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children: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:O.length})," ","modified ",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:we.length})," ",we.length===1?"entity":"entities"]})]}),O.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ms,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:J,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ts,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),c("div",{className:"overflow-hidden",children:[b==="branch"&&a&&n(Cg,{files:j,currentBranch:a,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:A,isEntityBeingAnalyzed:Z,isEntityQueued:X,sortOrder:x,onToggleFile:de=>F(de,A,T),onBranchChange:he,onGenerateSimulation:z,onSortChange:N,onAnalyzeAll:ye,analyzeAllDisabled:Le,analyzeAllText:Pe}),b==="uncommitted"&&n(Ng,{files:M,entityImpactMap:R,expandedFiles:A,isEntityBeingAnalyzed:Z,isEntityQueued:X,projectSlug:u,baseBranch:l,currentBranch:a,sortOrder:x,onToggleFile:de=>F(de,A,T),onShowFileDiff:I,onGenerateSimulation:z,onSortChange:N,onAnalyzeAll:ye,analyzeAllDisabled:Le,analyzeAllText:Pe})]}),D&&n(wg,{diffView:D,diffContent:Y,isLoading:L,entities:t,onClose:E}),g&&u&&n(ut,{projectSlug:u,onClose:()=>y(null)})]})})}),_g=Object.freeze(Object.defineProperty({__proto__:null,action:Ag,default:Pg,loader:kg,meta:Eg},Symbol.toStringTag,{value:"Module"})),N0={entry:{module:"/assets/entry.client-BSHEfydn.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/index-ChN9-fAY.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-D6oziHts.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/index-ChN9-fAY.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-C6PKeMYR.js","/assets/useReportContext-CpZgwliL.js","/assets/loader-circle-CTqLEAGU.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/book-open-PttOB2SF.js","/assets/useToast-Bv9JFvUO.js","/assets/useLastLogLine-COky1GVF.js","/assets/LogViewer-Bm3PmcCz.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/chevron-down-TJp6ofnp.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.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-CBoafmVs.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/useLastLogLine-COky1GVF.js","/assets/useCustomSizes-DNwUduNu.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-38yPijoD.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InteractivePreview-BDhPilK7.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-COky1GVF.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-DGgZjdFg.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InteractivePreview-BDhPilK7.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-COky1GVF.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-DfKzxuoe.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/terminal-BrCP7uQo.js","/assets/search-B8VUL8nl.js","/assets/chevron-down-TJp6ofnp.js","/assets/book-open-PttOB2SF.js","/assets/triangle-alert-BZz2NjYa.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DD1r_QU0.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/LogViewer-Bm3PmcCz.js","/assets/useLastLogLine-COky1GVF.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/loader-circle-CTqLEAGU.js","/assets/pause-D6vreykR.js","/assets/createLucideIcon-Ca9fAY46.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._-n38keI1k.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useLastLogLine-COky1GVF.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/InteractivePreview-BDhPilK7.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-BNLaXBHR.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/CopyButton-CA3JxPb7.js","/assets/LogViewer-Bm3PmcCz.js","/assets/useReportContext-CpZgwliL.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-DNwUduNu.js","/assets/ReportIssueModal-C6PKeMYR.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.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-CPoAg7Zo.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/chevron-down-TJp6ofnp.js","/assets/search-B8VUL8nl.js","/assets/loader-circle-CTqLEAGU.js","/assets/createLucideIcon-Ca9fAY46.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-C5lqplTC.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/ScenarioViewer-BNLaXBHR.js","/assets/InteractivePreview-BDhPilK7.js","/assets/useCustomSizes-DNwUduNu.js","/assets/LogViewer-Bm3PmcCz.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/useLastLogLine-COky1GVF.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-C6PKeMYR.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.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-B2X7lJgQ.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.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-B3TDXxnk.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useLastLogLine-COky1GVF.js","/assets/useToast-Bv9JFvUO.js","/assets/useReportContext-CpZgwliL.js","/assets/LogViewer-Bm3PmcCz.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/circle-check-CXhHQYrI.js","/assets/loader-circle-CTqLEAGU.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-DCHBwHou.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/terminal-BrCP7uQo.js","/assets/copy-6y9ALfGT.js","/assets/CopyButton-CA3JxPb7.js","/assets/search-B8VUL8nl.js","/assets/pause-D6vreykR.js","/assets/chevron-down-TJp6ofnp.js","/assets/book-open-PttOB2SF.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-Dk8wkAS7.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityItem-B86KKU7e.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/chevron-down-TJp6ofnp.js","/assets/search-B8VUL8nl.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/useToast-Bv9JFvUO.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-BZz2NjYa.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-BUvfJMNR.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.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-DXnyr8uP.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityItem-B86KKU7e.js","/assets/LogViewer-Bm3PmcCz.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/useToast-Bv9JFvUO.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-BZz2NjYa.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-d4e77269.js",version:"d4e77269",sri:void 0},S0="build/client",E0="/",A0={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},k0=!0,P0=!1,_0=[],M0={mode:"lazy",manifestPath:"/__manifest"},T0="/",j0={module:Nl},I0={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Fd},"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:Ud},"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:uu},"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:xu},"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:vh},"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:Nh},"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:Bh},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Wh},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Gh},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:sm},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:lm},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:um},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:pm},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:gm},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Pm},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:Im},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Lm},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:zm},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Um},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:tp},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:rp},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:cp},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:up},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:vp},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Np},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Ep},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Gp},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Qp},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:af},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:of},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:cf},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:vf},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Nf},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Af},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:If},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Rf},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Wf},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:og},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:hg},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:xg},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:_g}},$0=!1;export{_c as A,kc as B,Ce as C,ec as D,tc as E,Pt as F,Ul as G,Ys as H,zs as I,Bs as J,Gl as K,Kl as L,S0 as M,E0 as N,A0 as O,zl as P,k0 as Q,P0 as R,Mn as S,_0 as T,M0 as U,T0 as V,j0 as W,I0 as X,$0 as Y,N0 as Z,Dl as a,Tt as b,At as c,at as d,sn as e,Wr as f,Hr as g,Os as h,$l as i,uc as j,hc as k,mt as l,st as m,Hs as n,vc as o,jn as p,pt as q,Js as r,Vs as s,Ec as t,dt as u,Gs as v,Rt as w,qs as x,Ha as y,Tc as z};
|