@codeyam/codeyam-cli 0.1.0-staging.8aea589 → 0.1.0-staging.8c89b23
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 +2 -2
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +41 -36
- package/analyzer-template/packages/ai/index.ts +27 -7
- package/analyzer-template/packages/ai/package.json +6 -6
- package/analyzer-template/packages/ai/scripts/ai-test-matrix.mjs +424 -0
- package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +274 -8
- package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +279 -43
- package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +561 -20
- package/analyzer-template/packages/ai/src/lib/astScopes/nodeToSource.ts +19 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +53 -7
- 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 +48 -2
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1836 -142
- package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +328 -5
- package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +28 -11
- package/analyzer-template/packages/ai/src/lib/completionCall.ts +247 -66
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +4766 -775
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.ts +175 -7
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.ts +10 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +21 -4
- 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 +249 -81
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +152 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/DebugTracer.ts +224 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/PathManager.ts +203 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/README.md +294 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +163 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.ts +235 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +87 -8
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +229 -21
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.ts +62 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +166 -17
- 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 +455 -88
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/getFunctionCallRoot.ts +33 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/selectBestValue.ts +70 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.ts +113 -0
- package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -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/generateChangesEntityDocumentation.ts +20 -2
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +124 -158
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +139 -346
- package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +70 -7
- package/analyzer-template/packages/ai/src/lib/generateEntityDocumentation.ts +16 -2
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1513 -195
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +232 -295
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +677 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
- package/analyzer-template/packages/ai/src/lib/generateStatementAnalysis.ts +49 -72
- package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +170 -37
- package/analyzer-template/packages/ai/src/lib/getLLMCallStats.ts +0 -14
- 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/mergeJsonTypeDefinitions.ts +5 -0
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +135 -7
- package/analyzer-template/packages/ai/src/lib/modelInfo.ts +15 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +150 -31
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.ts +8 -33
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +54 -62
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +77 -150
- 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/generateEntityDocumentationGenerator.ts +8 -27
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +139 -40
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +16 -49
- 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/types/index.ts +2 -0
- package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +171 -2
- package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
- package/analyzer-template/packages/analyze/index.ts +6 -1
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +230 -54
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +132 -33
- package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
- package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +3 -1
- 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/getAllExportedNodes.ts +4 -2
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +49 -9
- 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 +785 -150
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +74 -39
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +26 -7
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findPreviousAnalysis.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findValidExistingAnalysis.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +29 -22
- package/analyzer-template/packages/analyze/src/lib/files/analyze/setActiveAnalysisBranches.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +26 -13
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +115 -20
- package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +69 -30
- package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +29 -11
- package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +50 -28
- package/analyzer-template/packages/analyze/src/lib/files/analyzeNextRoute.ts +9 -4
- package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +26 -39
- package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +135 -16
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1352 -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 +837 -99
- 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 +891 -39
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +166 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +84 -80
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +8 -4
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1896 -640
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +61 -6
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
- package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +3 -2
- 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/getPresignedUrl.d.ts +23 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts.map +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js +30 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.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 +10 -9
- package/analyzer-template/packages/aws/s3/index.ts +5 -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/getPresignedUrl.ts +62 -0
- package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
- package/analyzer-template/packages/database/client.ts +35 -0
- package/analyzer-template/packages/database/index.ts +94 -0
- package/analyzer-template/packages/database/package.json +31 -0
- package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +28 -0
- package/analyzer-template/packages/database/src/lib/analysisToDb.ts +59 -0
- package/analyzer-template/packages/database/src/lib/branchToDb.ts +24 -0
- package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +20 -0
- package/analyzer-template/packages/database/src/lib/commitToDb.ts +47 -0
- package/analyzer-template/packages/database/src/lib/fileToDb.ts +17 -0
- package/analyzer-template/packages/database/src/lib/kysely/db.ts +503 -0
- package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +108 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +67 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +88 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +164 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
- package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +275 -0
- package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +233 -0
- package/analyzer-template/packages/database/src/lib/loadBranch.ts +137 -0
- package/analyzer-template/packages/database/src/lib/loadCommit.ts +173 -0
- package/analyzer-template/packages/database/src/lib/loadCommits.ts +290 -0
- package/analyzer-template/packages/database/src/lib/loadEntities.ts +111 -0
- package/analyzer-template/packages/database/src/lib/loadEntity.ts +116 -0
- package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +178 -0
- package/analyzer-template/packages/database/src/lib/loadFile.ts +42 -0
- package/analyzer-template/packages/database/src/lib/loadFiles.ts +134 -0
- package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +96 -0
- package/analyzer-template/packages/database/src/lib/loadStatement.ts +23 -0
- package/analyzer-template/packages/database/src/lib/projectToDb.ts +35 -0
- package/analyzer-template/packages/database/src/lib/saveEntityStatements.ts +27 -0
- package/analyzer-template/packages/database/src/lib/saveFiles.ts +43 -0
- package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +35 -0
- package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +131 -0
- package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatus.ts +80 -0
- package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.ts +110 -0
- package/analyzer-template/packages/database/src/lib/updateProjectMetadata.ts +95 -0
- package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +18 -0
- package/analyzer-template/packages/generate/index.ts +3 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +44 -21
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.ts +18 -11
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +221 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +42 -9
- package/analyzer-template/packages/generate/src/lib/deepMerge.ts +29 -2
- package/analyzer-template/packages/generate/src/lib/directExecutionScript.ts +17 -2
- package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
- package/analyzer-template/packages/generate/src/lib/scenarioComponent.ts +6 -3
- package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
- package/analyzer-template/packages/github/dist/database/index.d.ts +87 -0
- package/analyzer-template/packages/github/dist/database/index.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/index.js +85 -0
- package/analyzer-template/packages/github/dist/database/index.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +19 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +26 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/backgroundJobToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/backgroundJobToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +18 -0
- package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +13 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +26 -0
- package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createOrUpdateBranchCommitStats.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createOrUpdateBranchCommitStats.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createProject.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createProject.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createRetryFetch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/createRetryFetch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToAnalysis.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToAnalysis.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToAnalysisBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToAnalysisBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToBackgroundJob.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToBackgroundJob.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToCommit.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToCommit.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToCommitBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToCommitBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToEntity.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToEntity.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToEntityBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToEntityBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToFile.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToFile.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToProject.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToProject.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToScenario.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToScenario.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToScenarioComment.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToScenarioComment.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToUserScenario.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/dbToUserScenario.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteEntities.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteEntities.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteFile.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteFile.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteScenarios.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/deleteScenarios.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/entityToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/entityToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +14 -0
- package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/generateSha.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/generateSha.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/jsonUpdateUtils.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/jsonUpdateUtils.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/aggregationHelpers.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/aggregationHelpers.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +73 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +378 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/schemaHelpers.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/schemaHelpers.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/sqliteBooleanPlugin.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/sqliteBooleanPlugin.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +89 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelationsTypes.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelationsTypes.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +97 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysisBranchesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysisBranchesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/backgroundJobsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/backgroundJobsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/branchesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/branchesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitBranchesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitBranchesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +48 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +47 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +60 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +33 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +29 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +68 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entityBranchesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entityBranchesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entityStatementsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entityStatementsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/filesTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/filesTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/githubPayloadsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/githubPayloadsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/githubUsersTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/githubUsersTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/projectsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/projectsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenarioCommentsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenarioCommentsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +66 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/statementsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/statementsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/teamsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/teamsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/userScenariosTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/userScenariosTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/userTeamsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/userTeamsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/usersTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/usersTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/upsertHelpers.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/upsertHelpers.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +16 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +174 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +144 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysisBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysisBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBackgroundJob.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBackgroundJob.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +100 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +118 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommitBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommitBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommitMetadata.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommitMetadata.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +15 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +219 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +13 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +76 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts +19 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js +72 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +123 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadFile.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadFile.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadFiles.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadFiles.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadMostRecentPreviousAnalysis.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadMostRecentPreviousAnalysis.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadProject.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadProject.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +65 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadScenario.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadScenario.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadStatement.d.ts +3 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadStatement.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadStatement.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/nullsToUndefines.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/nullsToUndefines.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +18 -0
- package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveBackgroundEvent.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveBackgroundEvent.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveEntityStatements.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveEntityStatements.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +33 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveStatement.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/saveStatement.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +18 -0
- package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/supabase.d.ts +4 -0
- package/analyzer-template/packages/github/dist/database/src/lib/supabase.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/supabase.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateBackgroundJobProgress.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateBackgroundJobProgress.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +13 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +87 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateEntityBranch.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateEntityBranch.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisMetadata.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisMetadata.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js +53 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +81 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateProjectMetadata.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/updateProjectMetadata.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalyses.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalyses.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalysesWithScenarios.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalysesWithScenarios.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalysisBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertAnalysisBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertBackgroundJob.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertBackgroundJob.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertCommitBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertCommitBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertCommits.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertCommits.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertEntities.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertEntities.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertEntityBranches.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertEntityBranches.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertFiles.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertFiles.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertGithubUser.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertGithubUser.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertProjects.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertProjects.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertScenarios.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/upsertScenarios.js.map +1 -0
- 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 +43 -21
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/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 +217 -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 +41 -9
- 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 +30 -2
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js +10 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js +5 -3
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js.map +1 -1
- package/analyzer-template/packages/github/dist/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/getCommitsFromGithub.js +1 -1
- 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 +11 -1
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncBranches.js +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncHeadBranches.js +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 +4 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPullRequest.js +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/updateCommitBranchesInDb.js +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/updateFilesInDb.js +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/enums/ProjectFramework.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -9
- 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 +4 -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 +8 -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 +21 -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/index.d.ts +3 -0
- package/analyzer-template/packages/github/dist/utils/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/index.js +4 -0
- package/analyzer-template/packages/github/dist/utils/index.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts +25 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js +40 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +65 -7
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.d.ts +13 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js +14 -2
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js +2 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts +12 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +14 -2
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +21 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +62 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- 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 +42 -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 +32 -3
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/buildStartCommand.d.ts +18 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/buildStartCommand.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/buildStartCommand.js +45 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/buildStartCommand.js.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/getWebappInfo.d.ts +26 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/getWebappInfo.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/getWebappInfo.js +67 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/getWebappInfo.js.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/index.d.ts +3 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/index.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/index.js +3 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/startCommand/index.js.map +1 -0
- package/analyzer-template/packages/github/package.json +2 -2
- package/analyzer-template/packages/github/src/lib/getCommitsFromGithub.ts +1 -1
- package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +15 -1
- package/analyzer-template/packages/github/src/lib/syncBranches.ts +1 -1
- package/analyzer-template/packages/github/src/lib/syncHeadBranches.ts +1 -1
- package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +3 -1
- package/analyzer-template/packages/github/src/lib/syncPullRequest.ts +1 -1
- package/analyzer-template/packages/github/src/lib/updateCommitBranchesInDb.ts +1 -1
- package/analyzer-template/packages/github/src/lib/updateFilesInDb.ts +1 -1
- 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/enums/ProjectFramework.ts +2 -0
- package/analyzer-template/packages/types/src/types/Analysis.ts +104 -9
- package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
- package/analyzer-template/packages/types/src/types/Entity.ts +4 -0
- package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +8 -0
- package/analyzer-template/packages/types/src/types/Scenario.ts +21 -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/package.json +5 -5
- package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
- package/analyzer-template/packages/ui-components/src/scenario-editor/components/DataItemEditor.tsx +1 -1
- 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/enums/ProjectFramework.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -9
- 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 +4 -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 +8 -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 +21 -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/index.d.ts +3 -0
- package/analyzer-template/packages/utils/dist/utils/index.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/index.js +4 -0
- package/analyzer-template/packages/utils/dist/utils/index.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts +25 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js +40 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +65 -7
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.d.ts +13 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js +14 -2
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js +2 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts +12 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +14 -2
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +21 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +62 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts +3 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +120 -4
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.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 +42 -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 +32 -3
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/buildStartCommand.d.ts +18 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/buildStartCommand.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/buildStartCommand.js +45 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/buildStartCommand.js.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/getWebappInfo.d.ts +26 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/getWebappInfo.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/getWebappInfo.js +67 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/getWebappInfo.js.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/index.d.ts +3 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/index.d.ts.map +1 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/index.js +3 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/startCommand/index.js.map +1 -0
- package/analyzer-template/packages/utils/index.ts +11 -0
- package/analyzer-template/packages/utils/src/lib/Semaphore.ts +42 -0
- package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +74 -9
- package/analyzer-template/packages/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.ts +20 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/getNextRoutePath.ts +2 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/getRemixRoutePath.ts +2 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.ts +17 -1
- package/analyzer-template/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.ts +1 -0
- package/analyzer-template/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.ts +67 -0
- package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +148 -3
- package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +43 -0
- package/analyzer-template/packages/utils/src/lib/safeFileName.ts +51 -3
- package/analyzer-template/packages/utils/src/lib/startCommand/buildStartCommand.ts +63 -0
- package/analyzer-template/packages/utils/src/lib/startCommand/getWebappInfo.ts +108 -0
- package/analyzer-template/packages/utils/src/lib/startCommand/index.ts +10 -0
- package/analyzer-template/playwright/capture.ts +103 -93
- package/analyzer-template/playwright/captureFromUrl.ts +121 -83
- package/analyzer-template/playwright/captureStatic.ts +2 -2
- package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
- package/analyzer-template/playwright/takeElementScreenshot.ts +48 -11
- package/analyzer-template/playwright/takeScreenshot.ts +38 -10
- package/analyzer-template/playwright/updateBackgroundJob.ts +1 -1
- package/analyzer-template/playwright/waitForServer.ts +21 -6
- package/analyzer-template/project/LazyFileStore.ts +1 -1
- package/analyzer-template/project/TESTING.md +83 -0
- package/analyzer-template/project/analyzeBaselineCommit.ts +10 -1
- package/analyzer-template/project/analyzeBranchCommit.ts +5 -1
- package/analyzer-template/project/analyzeFileEntities.ts +31 -1
- package/analyzer-template/project/analyzeRegularCommit.ts +10 -1
- package/analyzer-template/project/captureLibraryFunctionDirect.ts +30 -27
- package/analyzer-template/project/constructMockCode.ts +1836 -96
- package/analyzer-template/project/controller/startController.ts +16 -1
- package/analyzer-template/project/createEntitiesAndSortFiles.ts +98 -7
- package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
- package/analyzer-template/project/getFilesWithEntitiesFromRepo.ts +1 -1
- package/analyzer-template/project/getScenarioUrl.ts +73 -5
- package/analyzer-template/project/loadReadyToBeCaptured.ts +198 -38
- 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 +15 -15
- package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +97 -67
- package/analyzer-template/project/orchestrateCapture/SupabaseAnalysisLoader.ts +6 -6
- package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
- package/analyzer-template/project/orchestrateCapture.ts +93 -14
- package/analyzer-template/project/prepareRepo.ts +1 -1
- package/analyzer-template/project/reconcileMockDataKeys.ts +264 -3
- package/analyzer-template/project/runAnalysis.ts +12 -1
- package/analyzer-template/project/runMultiScenarioServer.ts +39 -19
- package/analyzer-template/project/runScenarioServer.ts +1 -5
- package/analyzer-template/project/serverOnlyModules.ts +413 -0
- package/analyzer-template/project/start.ts +97 -33
- package/analyzer-template/project/startScenarioCapture.ts +112 -41
- package/analyzer-template/project/startServer.ts +50 -70
- package/analyzer-template/project/trackGeneratedFiles.ts +41 -0
- package/analyzer-template/project/updateCommitBackgroundJob.ts +1 -1
- package/analyzer-template/project/utils/errorHandling.ts +1 -1
- package/analyzer-template/project/writeClientLogRoute.ts +125 -0
- package/analyzer-template/project/writeMockDataTsx.ts +765 -69
- package/analyzer-template/project/writeScenario.ts +1 -1
- package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
- package/analyzer-template/project/writeScenarioComponents.ts +2381 -179
- package/analyzer-template/project/writeScenarioFiles.ts +26 -0
- package/analyzer-template/project/writeSimpleRoot.ts +125 -2
- package/analyzer-template/project/writeUniversalMocks.ts +88 -9
- package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
- package/analyzer-template/scripts/defaultCmd.sh +9 -0
- package/analyzer-template/scripts/postbuild.cjs +12 -1
- package/analyzer-template/tsconfig.json +14 -1
- package/background/src/lib/local/createLocalAnalyzer.js +2 -30
- 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 +2 -2
- package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
- package/background/src/lib/virtualized/project/LazyFileStore.js +1 -1
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +8 -2
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js +3 -2
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeFileEntities.js +25 -2
- package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js +8 -2
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +4 -4
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
- package/background/src/lib/virtualized/project/constructMockCode.js +1603 -68
- 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 +83 -4
- 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/getFilesWithEntitiesFromRepo.js +1 -1
- package/background/src/lib/virtualized/project/getScenarioUrl.js +38 -3
- package/background/src/lib/virtualized/project/getScenarioUrl.js.map +1 -1
- package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +108 -6
- 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 +13 -7
- package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -49
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture.js +77 -15
- package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/prepareRepo.js +1 -1
- package/background/src/lib/virtualized/project/prepareRepo.js.map +1 -1
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +223 -3
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
- package/background/src/lib/virtualized/project/runAnalysis.js +10 -1
- package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js +36 -17
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
- package/background/src/lib/virtualized/project/serverOnlyModules.js +338 -0
- package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
- package/background/src/lib/virtualized/project/start.js +83 -30
- package/background/src/lib/virtualized/project/start.js.map +1 -1
- package/background/src/lib/virtualized/project/startScenarioCapture.js +84 -31
- package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/startServer.js +40 -68
- package/background/src/lib/virtualized/project/startServer.js.map +1 -1
- package/background/src/lib/virtualized/project/trackGeneratedFiles.js +30 -0
- package/background/src/lib/virtualized/project/trackGeneratedFiles.js.map +1 -0
- package/background/src/lib/virtualized/project/updateCommitBackgroundJob.js +1 -1
- package/background/src/lib/virtualized/project/utils/errorHandling.js +1 -1
- package/background/src/lib/virtualized/project/writeClientLogRoute.js +110 -0
- package/background/src/lib/virtualized/project/writeClientLogRoute.js.map +1 -0
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +652 -60
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenario.js +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 +1743 -117
- 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 +113 -2
- package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
- package/background/src/lib/virtualized/project/writeUniversalMocks.js +72 -8
- package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +386 -9
- package/codeyam-cli/scripts/apply-setup.js.map +1 -1
- package/codeyam-cli/scripts/extract-setup.js +1 -1
- package/codeyam-cli/scripts/populateEntityTimestamps.js +1 -1
- package/codeyam-cli/scripts/populateEntityTimestamps.js.map +1 -1
- package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
- package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
- package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
- package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
- package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
- package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
- package/codeyam-cli/src/cli.js +66 -17
- package/codeyam-cli/src/cli.js.map +1 -1
- package/codeyam-cli/src/codeyam-cli.js +18 -2
- package/codeyam-cli/src/codeyam-cli.js.map +1 -1
- package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js +47 -0
- package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js +71 -0
- package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js +30 -0
- package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js +51 -0
- package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/editor.statePersistence.test.js +55 -0
- package/codeyam-cli/src/commands/__tests__/editor.statePersistence.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +56 -0
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +137 -47
- package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
- package/codeyam-cli/src/commands/analyze.js +22 -10
- package/codeyam-cli/src/commands/analyze.js.map +1 -1
- package/codeyam-cli/src/commands/baseline.js +176 -0
- package/codeyam-cli/src/commands/baseline.js.map +1 -0
- package/codeyam-cli/src/commands/debug.js +253 -0
- package/codeyam-cli/src/commands/debug.js.map +1 -0
- package/codeyam-cli/src/commands/default.js +43 -35
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/editor.js +6311 -0
- package/codeyam-cli/src/commands/editor.js.map +1 -0
- package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js +23 -0
- package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js.map +1 -0
- package/codeyam-cli/src/commands/editorIsolateArgs.js +25 -0
- package/codeyam-cli/src/commands/editorIsolateArgs.js.map +1 -0
- package/codeyam-cli/src/commands/entities.js +1 -1
- package/codeyam-cli/src/commands/generate-data-structure.js +17 -8
- package/codeyam-cli/src/commands/generate-data-structure.js.map +1 -1
- package/codeyam-cli/src/commands/init.js +169 -312
- package/codeyam-cli/src/commands/init.js.map +1 -1
- package/codeyam-cli/src/commands/memory.js +278 -0
- package/codeyam-cli/src/commands/memory.js.map +1 -0
- package/codeyam-cli/src/commands/recapture.js +228 -0
- package/codeyam-cli/src/commands/recapture.js.map +1 -0
- package/codeyam-cli/src/commands/report.js +150 -0
- package/codeyam-cli/src/commands/report.js.map +1 -0
- package/codeyam-cli/src/commands/setup-sandbox.js +167 -0
- package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -0
- package/codeyam-cli/src/commands/setup-simulations.js +284 -0
- package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
- 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/suggest.js +1 -1
- package/codeyam-cli/src/commands/telemetry.js +37 -0
- package/codeyam-cli/src/commands/telemetry.js.map +1 -0
- package/codeyam-cli/src/commands/test-startup.js +17 -6
- package/codeyam-cli/src/commands/test-startup.js.map +1 -1
- package/codeyam-cli/src/commands/verify.js +14 -2
- package/codeyam-cli/src/commands/verify.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/data/designSystems.js +27 -0
- package/codeyam-cli/src/data/designSystems.js.map +1 -0
- package/codeyam-cli/src/data/techStacks.js +77 -0
- package/codeyam-cli/src/data/techStacks.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +173 -0
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
- package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js +6 -6
- package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/devServerState.test.js +134 -0
- package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorApi.test.js +181 -0
- package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +4160 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js +76 -0
- package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
- package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js +137 -0
- package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js +100 -0
- package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +304 -0
- package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +194 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js +381 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js +67 -0
- package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
- package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +542 -0
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +594 -0
- package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorMigration.test.js +435 -0
- package/codeyam-cli/src/utils/__tests__/editorMigration.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
- package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +217 -0
- package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +361 -0
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +250 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js +941 -0
- package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +411 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +1768 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +413 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js +143 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js +66 -0
- package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js +53 -0
- package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +2121 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/entityVersioning.test.js +2 -2
- package/codeyam-cli/src/utils/__tests__/envFile.test.js +125 -0
- package/codeyam-cli/src/utils/__tests__/envFile.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/fileWatcher.batch.test.js +2 -2
- package/codeyam-cli/src/utils/__tests__/fileWatcher.multiversion.test.js +58 -30
- package/codeyam-cli/src/utils/__tests__/fileWatcher.multiversion.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/fileWatcher.optimization.test.js +2 -2
- package/codeyam-cli/src/utils/__tests__/fileWatcher.versioning.test.js +2 -2
- package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
- package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js +177 -0
- package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/handoffContext.test.js +500 -0
- package/codeyam-cli/src/utils/__tests__/handoffContext.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +122 -0
- package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js +302 -0
- package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
- package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +129 -0
- package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js +9 -0
- package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
- package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js +127 -0
- package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js +118 -0
- package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +284 -0
- package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
- package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +672 -0
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/screenshotHash.test.js +84 -0
- package/codeyam-cli/src/utils/__tests__/screenshotHash.test.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 +175 -74
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/telemetry.test.js +159 -0
- package/codeyam-cli/src/utils/__tests__/telemetry.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
- package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/testRunner.test.js +216 -0
- package/codeyam-cli/src/utils/__tests__/testRunner.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +148 -0
- package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
- package/codeyam-cli/src/utils/analysisRunner.js +70 -24
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/analyzer.js +50 -2
- package/codeyam-cli/src/utils/analyzer.js.map +1 -1
- package/codeyam-cli/src/utils/analyzerFinalization.js +100 -0
- package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
- package/codeyam-cli/src/utils/backgroundServer.js +205 -32
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/buildFlags.js +4 -0
- package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
- package/codeyam-cli/src/utils/changeDetection.js +1 -1
- package/codeyam-cli/src/utils/cleanupAnalysisFiles.js +2 -2
- package/codeyam-cli/src/utils/cleanupAnalysisFiles.js.map +1 -1
- package/codeyam-cli/src/utils/database.js +129 -8
- package/codeyam-cli/src/utils/database.js.map +1 -1
- package/codeyam-cli/src/utils/designSystemShowcase.js +810 -0
- package/codeyam-cli/src/utils/designSystemShowcase.js.map +1 -0
- package/codeyam-cli/src/utils/devModeEvents.js +40 -0
- package/codeyam-cli/src/utils/devModeEvents.js.map +1 -0
- package/codeyam-cli/src/utils/devServerState.js +71 -0
- package/codeyam-cli/src/utils/devServerState.js.map +1 -0
- package/codeyam-cli/src/utils/editorApi.js +95 -0
- package/codeyam-cli/src/utils/editorApi.js.map +1 -0
- package/codeyam-cli/src/utils/editorAudit.js +849 -0
- package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
- package/codeyam-cli/src/utils/editorBroadcastViewport.js +26 -0
- package/codeyam-cli/src/utils/editorBroadcastViewport.js.map +1 -0
- package/codeyam-cli/src/utils/editorCapture.js +102 -0
- package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
- package/codeyam-cli/src/utils/editorDeleteScenario.js +67 -0
- package/codeyam-cli/src/utils/editorDeleteScenario.js.map +1 -0
- package/codeyam-cli/src/utils/editorDevServer.js +197 -0
- package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
- package/codeyam-cli/src/utils/editorEntityChangeStatus.js +50 -0
- package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
- package/codeyam-cli/src/utils/editorEntityHelpers.js +144 -0
- package/codeyam-cli/src/utils/editorEntityHelpers.js.map +1 -0
- package/codeyam-cli/src/utils/editorGuard.js +36 -0
- package/codeyam-cli/src/utils/editorGuard.js.map +1 -0
- package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
- package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
- package/codeyam-cli/src/utils/editorJournal.js +225 -0
- package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
- package/codeyam-cli/src/utils/editorLoaderHelpers.js +152 -0
- package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
- package/codeyam-cli/src/utils/editorMigration.js +224 -0
- package/codeyam-cli/src/utils/editorMigration.js.map +1 -0
- package/codeyam-cli/src/utils/editorMockState.js +248 -0
- package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
- package/codeyam-cli/src/utils/editorPreloadHelpers.js +135 -0
- package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
- package/codeyam-cli/src/utils/editorPreview.js +139 -0
- package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
- package/codeyam-cli/src/utils/editorRecapture.js +109 -0
- package/codeyam-cli/src/utils/editorRecapture.js.map +1 -0
- package/codeyam-cli/src/utils/editorRoadmap.js +530 -0
- package/codeyam-cli/src/utils/editorRoadmap.js.map +1 -0
- package/codeyam-cli/src/utils/editorScenarioSwitch.js +149 -0
- package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
- package/codeyam-cli/src/utils/editorScenarios.js +687 -0
- package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js +475 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
- package/codeyam-cli/src/utils/editorShouldRevalidate.js +21 -0
- package/codeyam-cli/src/utils/editorShouldRevalidate.js.map +1 -0
- package/codeyam-cli/src/utils/entityCache.js +1 -1
- package/codeyam-cli/src/utils/entityChangeStatus.js +394 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js +227 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
- package/codeyam-cli/src/utils/entityMetadata.js +1 -1
- package/codeyam-cli/src/utils/entityVersioning.js +1 -1
- package/codeyam-cli/src/utils/envFile.js +90 -0
- package/codeyam-cli/src/utils/envFile.js.map +1 -0
- package/codeyam-cli/src/utils/fileMetadata.js +5 -0
- package/codeyam-cli/src/utils/fileMetadata.js.map +1 -1
- package/codeyam-cli/src/utils/fileWatcher.js +65 -11
- package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
- package/codeyam-cli/src/utils/generateReport.js +366 -0
- package/codeyam-cli/src/utils/generateReport.js.map +1 -0
- package/codeyam-cli/src/utils/git.js +182 -0
- package/codeyam-cli/src/utils/git.js.map +1 -0
- package/codeyam-cli/src/utils/glossaryAdd.js +74 -0
- package/codeyam-cli/src/utils/glossaryAdd.js.map +1 -0
- package/codeyam-cli/src/utils/handoffContext.js +257 -0
- package/codeyam-cli/src/utils/handoffContext.js.map +1 -0
- package/codeyam-cli/src/utils/install-skills.js +164 -37
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/interactiveSyncWatcher.js +126 -0
- package/codeyam-cli/src/utils/interactiveSyncWatcher.js.map +1 -0
- package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
- package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
- package/codeyam-cli/src/utils/manualEntityAnalysis.js +196 -0
- package/codeyam-cli/src/utils/manualEntityAnalysis.js.map +1 -0
- package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
- package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
- package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
- package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
- package/codeyam-cli/src/utils/pathIgnoring.js +19 -7
- package/codeyam-cli/src/utils/pathIgnoring.js.map +1 -1
- package/codeyam-cli/src/utils/progress.js +8 -1
- package/codeyam-cli/src/utils/progress.js.map +1 -1
- package/codeyam-cli/src/utils/project.js +15 -5
- package/codeyam-cli/src/utils/project.js.map +1 -1
- package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js +14 -14
- package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js.map +1 -1
- package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js +159 -0
- package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js.map +1 -0
- package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js +3 -2
- package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js.map +1 -1
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +60 -0
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
- package/codeyam-cli/src/utils/queue/heartbeat.js +14 -6
- package/codeyam-cli/src/utils/queue/heartbeat.js.map +1 -1
- package/codeyam-cli/src/utils/queue/job.js +367 -31
- package/codeyam-cli/src/utils/queue/job.js.map +1 -1
- package/codeyam-cli/src/utils/queue/manager.js +104 -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/registerScenarioResult.js +52 -0
- package/codeyam-cli/src/utils/registerScenarioResult.js.map +1 -0
- package/codeyam-cli/src/utils/requireSimulations.js +10 -0
- package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
- package/codeyam-cli/src/utils/routePatternMatching.js +129 -0
- package/codeyam-cli/src/utils/routePatternMatching.js.map +1 -0
- 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 +229 -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 +74 -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 +376 -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 +113 -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 +116 -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 +44 -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__/parser.test.js +83 -0
- package/codeyam-cli/src/utils/rules/__tests__/parser.test.js.map +1 -0
- package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +118 -0
- package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
- package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js +72 -0
- package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.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/__tests__/sourceFiles.test.js +76 -0
- package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
- package/codeyam-cli/src/utils/rules/index.js +7 -0
- package/codeyam-cli/src/utils/rules/index.js.map +1 -0
- package/codeyam-cli/src/utils/rules/parser.js +93 -0
- package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js +49 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
- package/codeyam-cli/src/utils/rules/rulePlacement.js +65 -0
- package/codeyam-cli/src/utils/rules/rulePlacement.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/sourceFiles.js +43 -0
- package/codeyam-cli/src/utils/rules/sourceFiles.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/sandbox.js +190 -0
- package/codeyam-cli/src/utils/sandbox.js.map +1 -0
- package/codeyam-cli/src/utils/scenarioCoverage.js +77 -0
- package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
- package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
- package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
- package/codeyam-cli/src/utils/scenariosManifest.js +313 -0
- package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
- package/codeyam-cli/src/utils/screenshotHash.js +26 -0
- package/codeyam-cli/src/utils/screenshotHash.js.map +1 -0
- package/codeyam-cli/src/utils/serverState.js +94 -12
- package/codeyam-cli/src/utils/serverState.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +96 -41
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/simulationGateMiddleware.js +175 -0
- package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
- package/codeyam-cli/src/utils/slugUtils.js +25 -0
- package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
- package/codeyam-cli/src/utils/syncMocksMiddleware.js +7 -26
- package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
- package/codeyam-cli/src/utils/syncUncommittedEntities.js +1 -1
- package/codeyam-cli/src/utils/syncUniversalMocks.js +1 -1
- package/codeyam-cli/src/utils/telemetry.js +106 -0
- package/codeyam-cli/src/utils/telemetry.js.map +1 -0
- package/codeyam-cli/src/utils/telemetryMiddleware.js +22 -0
- package/codeyam-cli/src/utils/telemetryMiddleware.js.map +1 -0
- package/codeyam-cli/src/utils/testResultCache.js +53 -0
- package/codeyam-cli/src/utils/testResultCache.js.map +1 -0
- package/codeyam-cli/src/utils/testResultCache.server.js +81 -0
- package/codeyam-cli/src/utils/testResultCache.server.js.map +1 -0
- package/codeyam-cli/src/utils/testResultCache.server.test.js +187 -0
- package/codeyam-cli/src/utils/testResultCache.server.test.js.map +1 -0
- package/codeyam-cli/src/utils/testResultCache.test.js +230 -0
- package/codeyam-cli/src/utils/testResultCache.test.js.map +1 -0
- package/codeyam-cli/src/utils/testRunner.js +350 -0
- package/codeyam-cli/src/utils/testRunner.js.map +1 -0
- package/codeyam-cli/src/utils/transcriptPruning.js +67 -0
- package/codeyam-cli/src/utils/transcriptPruning.js.map +1 -0
- package/codeyam-cli/src/utils/versionInfo.js +67 -15
- package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
- package/codeyam-cli/src/utils/webappDetection.js +39 -3
- package/codeyam-cli/src/utils/webappDetection.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/__tests__/api.interactive-switch-scenario.test.js +99 -0
- package/codeyam-cli/src/webserver/__tests__/api.interactive-switch-scenario.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +35 -0
- package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +107 -0
- package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
- package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +762 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +315 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js +135 -0
- package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js +86 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/database.js +210 -36
- package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/dbNotifier.js +3 -1
- package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/git.js +397 -0
- package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
- package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js +34 -0
- package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js.map +1 -0
- package/codeyam-cli/src/webserver/app/types/editor.js +8 -0
- package/codeyam-cli/src/webserver/app/types/editor.js.map +1 -0
- package/codeyam-cli/src/webserver/backgroundServer.js +191 -47
- package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/webserver/bootstrap.js +60 -0
- package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/CopyButton-DTBZZfSk.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-BxclONWq.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-CQgyEGV-.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BsnEOJZ_.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-ByaELMbv.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-6WjVfhxX.js +25 -0
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-ChX-Hp7W.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-By5zI316.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-C-9zQdXg.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/MiniClaudeChat-Bs2_Oua4.js +36 -0
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-DQsceHVv.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DThcm_9M.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-Cl4oOA3A.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/Spinner-CIil5-gb.js +34 -0
- package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-CK7-NaPZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-BqkA9zyZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/_index-DnOgyseQ.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DqM9hbNE.js +27 -0
- package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
- package/codeyam-cli/src/webserver/build/client/assets/addon-web-links-C58dYPwR.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
- package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-B8NCeOrm.js +22 -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.dev-mode-events-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-capture-scenario-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-client-errors-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-commit-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-dev-server-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-entity-status-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-github-verify-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-handoff-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-hosting-verify-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-entry-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-image._-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-screenshot-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-update-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-recapture-stale-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-refresh-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-register-scenario-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-rename-scenario-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-roadmap-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-scenario-data-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-seed-state-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-data-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-image._-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-prompt-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-schema-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-session-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-switch-scenario-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-test-results-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-verify-routes-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.generate-report-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.interactive-switch-scenario-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-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.rule-path-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-BFSIqZgO.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-B9fDzFVh.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chunk-UVKPFVEO-Bmq2apuh.js +43 -0
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-DLPObLUx.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/codeyam-name-logo-CvKwUgHo.svg +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/copy-DXEmO0TD.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BwyFiRot.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-Coe5NhbS.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DoA97ML3.svg +4 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-iRhRIFlp.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor._tab-BZPBzV73.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-D4cIaQC3.js +161 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-C6fEYHrh.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-pc-vc6wO.js +24 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-C8AyYgYT.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DziaVQX1.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BTcpgIpC.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-D_O_ajfZ.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-j1Vi0bco.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-Daa96Fr1.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-kuny2Q_s.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-DgCZPMie.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-D4iGjX2m.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-BliGSSpl.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-SqjQKTdH.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-vyrZD2g4.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/jsx-runtime-D_zvdyIk.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/labs-c3yLxSEp.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D-q28GLF.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-985e63d6.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/memory-CEWIUC4t.js +101 -0
- package/codeyam-cli/src/webserver/build/client/assets/pause-BP6fitdh.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-BRyJWJBA.js +80 -0
- package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/search-BooqacKS.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-BM0nbryO.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-ovy6FjRY.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/terminal-DHemCJIs.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-D87ekDl8.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-Dk0Tciqg.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-C8QvIe05.js +2 -0
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-jkCytuYz.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/useToast-BgqkixU9.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
- package/codeyam-cli/src/webserver/build/client/sound-test.html +98 -0
- package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-RX_oAulJ.js +16 -0
- package/codeyam-cli/src/webserver/build/server/assets/index-DRb-tJ77.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/init-CzFOE1qs.js +14 -0
- package/codeyam-cli/src/webserver/build/server/assets/progress-CHTtrxFG.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-CPKq4t0v.js +765 -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 +40 -8
- package/codeyam-cli/src/webserver/devServer.js.map +1 -1
- package/codeyam-cli/src/webserver/editorProxy.js +1101 -0
- package/codeyam-cli/src/webserver/editorProxy.js.map +1 -0
- package/codeyam-cli/src/webserver/idleDetector.js +130 -0
- package/codeyam-cli/src/webserver/idleDetector.js.map +1 -0
- package/codeyam-cli/src/webserver/mockStateEvents.js +28 -0
- package/codeyam-cli/src/webserver/mockStateEvents.js.map +1 -0
- package/codeyam-cli/src/webserver/public/sound-test.html +98 -0
- package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +414 -0
- package/codeyam-cli/src/webserver/scripts/journalCapture.ts +283 -0
- package/codeyam-cli/src/webserver/server.js +481 -26
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +985 -0
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -0
- package/codeyam-cli/templates/__tests__/editor-step-hook.prompt-capture.test.ts +118 -0
- package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
- package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
- package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
- package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
- package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
- package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
- package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
- package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
- package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
- package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
- package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
- package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
- package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
- package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
- package/codeyam-cli/templates/codeyam-editor-claude.md +149 -0
- package/codeyam-cli/templates/codeyam-editor-codex.md +61 -0
- package/codeyam-cli/templates/codeyam-editor-gemini.md +59 -0
- package/codeyam-cli/templates/codeyam-editor-reference.md +216 -0
- package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
- package/codeyam-cli/templates/commands/codeyam-diagnose.md +481 -0
- package/codeyam-cli/templates/design-systems/clean-dashboard-design-system.md +255 -0
- package/codeyam-cli/templates/design-systems/editorial-design-system.md +267 -0
- package/codeyam-cli/templates/design-systems/mono-brutalist-design-system.md +256 -0
- package/codeyam-cli/templates/design-systems/neo-brutalist-design-system.md +294 -0
- package/codeyam-cli/templates/editor-step-hook.py +368 -0
- package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +288 -0
- package/codeyam-cli/templates/expo-react-native/README.md +41 -0
- package/codeyam-cli/templates/expo-react-native/__tests__/.gitkeep +0 -0
- package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +15 -0
- package/codeyam-cli/templates/expo-react-native/app/index.tsx +36 -0
- package/codeyam-cli/templates/expo-react-native/app.json +29 -0
- package/codeyam-cli/templates/expo-react-native/babel.config.js +10 -0
- package/codeyam-cli/templates/expo-react-native/gitignore +14 -0
- package/codeyam-cli/templates/expo-react-native/global.css +10 -0
- package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
- package/codeyam-cli/templates/expo-react-native/lib/theme.ts +73 -0
- package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
- package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
- package/codeyam-cli/templates/expo-react-native/package.json +54 -0
- package/codeyam-cli/templates/expo-react-native/patches/expo-modules-autolinking+3.0.24.patch +29 -0
- package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
- package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
- package/codeyam-cli/templates/hooks/staleness-check.sh +43 -0
- package/codeyam-cli/templates/isolation-route/expo-router.tsx.template +54 -0
- package/codeyam-cli/templates/isolation-route/next-app.tsx.template +80 -0
- package/codeyam-cli/templates/isolation-route/next-pages.tsx.template +79 -0
- package/codeyam-cli/templates/isolation-route/vite-react.tsx.template +78 -0
- package/codeyam-cli/templates/msw/browser-setup.ts.template +47 -0
- package/codeyam-cli/templates/msw/handler-router.ts.template +47 -0
- package/codeyam-cli/templates/msw/server-setup.ts.template +52 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/api/todos/route.ts +17 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/globals.css +26 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/layout.tsx +34 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +24 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/page.tsx +10 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/eslint.config.mjs +11 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +65 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/next.config.ts +14 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +39 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/postcss.config.mjs +7 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/schema.prisma +27 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +40 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma.config.ts +12 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +140 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/tsconfig.json +34 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/SUPABASE_SETUP.md +104 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
- package/codeyam-cli/templates/prompts/conversation-guidance.txt +44 -0
- package/codeyam-cli/templates/prompts/conversation-prompt.txt +28 -0
- package/codeyam-cli/templates/prompts/interruption-prompt.txt +31 -0
- package/codeyam-cli/templates/prompts/stale-rules-prompt.txt +24 -0
- package/codeyam-cli/templates/rule-notification-hook.py +83 -0
- package/codeyam-cli/templates/rule-reflection-hook.py +647 -0
- package/codeyam-cli/templates/rules-instructions.md +78 -0
- package/codeyam-cli/templates/seed-adapters/supabase.ts +363 -0
- package/codeyam-cli/templates/skills/codeyam-debug/SKILL.md +601 -0
- package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +237 -0
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +244 -0
- package/codeyam-cli/templates/skills/codeyam-memory/SKILL.md +611 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
- package/codeyam-cli/templates/skills/codeyam-new-rule/SKILL.md +11 -0
- package/codeyam-cli/templates/skills/codeyam-setup/SKILL.md +600 -0
- package/codeyam-cli/templates/skills/codeyam-sim/SKILL.md +222 -0
- package/codeyam-cli/templates/skills/codeyam-test/SKILL.md +178 -0
- package/codeyam-cli/templates/skills/codeyam-verify/SKILL.md +179 -0
- package/package.json +43 -34
- package/packages/ai/index.js +9 -8
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +211 -6
- 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 +207 -40
- 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 +407 -20
- package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
- package/packages/ai/src/lib/astScopes/nodeToSource.js +16 -0
- package/packages/ai/src/lib/astScopes/nodeToSource.js.map +1 -1
- package/packages/ai/src/lib/astScopes/paths.js +51 -7
- package/packages/ai/src/lib/astScopes/paths.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 +31 -1
- 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 +1401 -102
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
- package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
- package/packages/ai/src/lib/checkAllAttributes.js +23 -10
- package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
- package/packages/ai/src/lib/completionCall.js +188 -38
- package/packages/ai/src/lib/completionCall.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +3630 -524
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js +164 -2
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js +9 -2
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
- 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 +184 -58
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +122 -0
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js +176 -0
- package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/PathManager.js +178 -0
- package/packages/ai/src/lib/dataStructure/helpers/PathManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +140 -0
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js +199 -0
- package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +80 -6
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +198 -15
- 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/coercePrimitivesToArraysBySchema.js +54 -0
- package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +145 -15
- 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 +385 -79
- 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/dataStructure/helpers/getFunctionCallRoot.js +28 -3
- package/packages/ai/src/lib/dataStructure/helpers/getFunctionCallRoot.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js +62 -0
- package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js +34 -0
- package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js +90 -0
- package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js.map +1 -0
- package/packages/ai/src/lib/dataStructureChunking.js +130 -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/generateChangesEntityDocumentation.js +19 -1
- package/packages/ai/src/lib/generateChangesEntityDocumentation.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js +111 -152
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarios.js +131 -322
- package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateEntityDataStructure.js +56 -6
- package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
- package/packages/ai/src/lib/generateEntityDocumentation.js +15 -1
- package/packages/ai/src/lib/generateEntityDocumentation.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +1193 -181
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +209 -269
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +484 -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 +1807 -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/generateStatementAnalysis.js +47 -72
- package/packages/ai/src/lib/generateStatementAnalysis.js.map +1 -1
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js +97 -22
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
- package/packages/ai/src/lib/getLLMCallStats.js +0 -14
- package/packages/ai/src/lib/getLLMCallStats.js.map +1 -1
- package/packages/ai/src/lib/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/mergeJsonTypeDefinitions.js +5 -0
- package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +104 -6
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/modelInfo.js +15 -0
- package/packages/ai/src/lib/modelInfo.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
- package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +118 -23
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js +8 -33
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +36 -42
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +49 -99
- 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/generateEntityDocumentationGenerator.js +8 -27
- package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +103 -29
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +12 -31
- 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/types/index.js +2 -0
- package/packages/ai/src/lib/types/index.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js +36 -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 +2 -1
- package/packages/analyze/index.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +196 -41
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/ProjectAnalyzer.js +109 -30
- 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/index.js +4 -2
- package/packages/analyze/src/lib/asts/index.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/getNodeType.js +2 -1
- package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/index.js +3 -1
- 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/getAllExportedNodes.js +3 -2
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExportedNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +41 -9
- 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 +608 -105
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +60 -28
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +15 -3
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/findPreviousAnalysis.js +1 -1
- package/packages/analyze/src/lib/files/analyze/findValidExistingAnalysis.js +1 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +24 -10
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/setActiveAnalysisBranches.js +1 -1
- package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +19 -8
- package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +75 -21
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeChange.js +43 -20
- package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeEntity.js +20 -13
- package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeInitial.js +31 -19
- package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeNextRoute.js +6 -2
- package/packages/analyze/src/lib/files/analyzeNextRoute.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeRemixRoute.js +22 -26
- 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 +103 -8
- package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +907 -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 +646 -72
- 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 +617 -36
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +104 -0
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +61 -67
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +8 -4
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +1523 -503
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +49 -6
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/setImportedExports.js +3 -2
- 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/index.js +85 -0
- package/packages/database/index.js.map +1 -0
- package/packages/database/src/lib/analysisBranchToDb.js +19 -0
- package/packages/database/src/lib/analysisBranchToDb.js.map +1 -0
- package/packages/database/src/lib/analysisToDb.js +26 -0
- package/packages/database/src/lib/analysisToDb.js.map +1 -0
- package/packages/database/src/lib/backgroundJobToDb.js.map +1 -0
- package/packages/database/src/lib/branchToDb.js +18 -0
- package/packages/database/src/lib/branchToDb.js.map +1 -0
- package/packages/database/src/lib/commitBranchToDb.js +13 -0
- package/packages/database/src/lib/commitBranchToDb.js.map +1 -0
- package/packages/database/src/lib/commitToDb.js +26 -0
- package/packages/database/src/lib/commitToDb.js.map +1 -0
- package/packages/database/src/lib/createOrUpdateBranchCommitStats.js.map +1 -0
- package/packages/database/src/lib/createProject.js.map +1 -0
- package/packages/database/src/lib/createRetryFetch.js.map +1 -0
- package/packages/database/src/lib/dbToAnalysis.js.map +1 -0
- package/packages/database/src/lib/dbToAnalysisBranch.js.map +1 -0
- package/packages/database/src/lib/dbToBackgroundJob.js.map +1 -0
- package/packages/database/src/lib/dbToBranch.js.map +1 -0
- package/packages/database/src/lib/dbToCommit.js.map +1 -0
- package/packages/database/src/lib/dbToCommitBranch.js.map +1 -0
- package/packages/database/src/lib/dbToEntity.js.map +1 -0
- package/packages/database/src/lib/dbToEntityBranch.js.map +1 -0
- package/packages/database/src/lib/dbToFile.js.map +1 -0
- package/packages/database/src/lib/dbToProject.js.map +1 -0
- package/packages/database/src/lib/dbToScenario.js.map +1 -0
- package/packages/database/src/lib/dbToScenarioComment.js.map +1 -0
- package/packages/database/src/lib/dbToUserScenario.js.map +1 -0
- package/packages/database/src/lib/deleteBranch.js.map +1 -0
- package/packages/database/src/lib/deleteEntities.js.map +1 -0
- package/packages/database/src/lib/deleteFile.js.map +1 -0
- package/packages/database/src/lib/deleteScenarios.js.map +1 -0
- package/packages/database/src/lib/entityToDb.js.map +1 -0
- package/packages/database/src/lib/fileToDb.js +14 -0
- package/packages/database/src/lib/fileToDb.js.map +1 -0
- package/packages/database/src/lib/generateSha.js.map +1 -0
- package/packages/database/src/lib/jsonUpdateUtils.js.map +1 -0
- package/packages/database/src/lib/kysely/aggregationHelpers.js.map +1 -0
- package/packages/database/src/lib/kysely/db.js +378 -0
- package/packages/database/src/lib/kysely/db.js.map +1 -0
- package/packages/database/src/lib/kysely/schemaHelpers.js.map +1 -0
- package/packages/database/src/lib/kysely/sqliteBooleanPlugin.js.map +1 -0
- package/packages/database/src/lib/kysely/tableRelations.js.map +1 -0
- package/packages/database/src/lib/kysely/tableRelationsTypes.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/analysesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/analysisBranchesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/backgroundJobsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/branchesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/commitBranchesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/commitsTable.js +47 -0
- package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js +33 -0
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/entitiesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/entityBranchesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/entityStatementsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/filesTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/githubPayloadsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/githubUsersTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
- package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/projectsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/scenarioCommentsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/scenariosTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/statementsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/teamsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/userScenariosTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/userTeamsTable.js.map +1 -0
- package/packages/database/src/lib/kysely/tables/usersTable.js.map +1 -0
- package/packages/database/src/lib/kysely/upsertHelpers.js.map +1 -0
- package/packages/database/src/lib/loadAnalyses.js +174 -0
- package/packages/database/src/lib/loadAnalyses.js.map +1 -0
- package/packages/database/src/lib/loadAnalysis.js +144 -0
- package/packages/database/src/lib/loadAnalysis.js.map +1 -0
- package/packages/database/src/lib/loadAnalysisBranches.js.map +1 -0
- package/packages/database/src/lib/loadBackgroundJob.js.map +1 -0
- package/packages/database/src/lib/loadBranch.js +100 -0
- package/packages/database/src/lib/loadBranch.js.map +1 -0
- package/packages/database/src/lib/loadBranches.js.map +1 -0
- package/packages/database/src/lib/loadCommit.js +118 -0
- package/packages/database/src/lib/loadCommit.js.map +1 -0
- package/packages/database/src/lib/loadCommitBranches.js.map +1 -0
- package/packages/database/src/lib/loadCommitMetadata.js.map +1 -0
- package/packages/database/src/lib/loadCommits.js +219 -0
- package/packages/database/src/lib/loadCommits.js.map +1 -0
- package/packages/database/src/lib/loadEntities.js +76 -0
- package/packages/database/src/lib/loadEntities.js.map +1 -0
- package/packages/database/src/lib/loadEntity.js +72 -0
- package/packages/database/src/lib/loadEntity.js.map +1 -0
- package/packages/database/src/lib/loadEntityBranches.js +123 -0
- package/packages/database/src/lib/loadEntityBranches.js.map +1 -0
- package/packages/database/src/lib/loadFile.js.map +1 -0
- package/packages/database/src/lib/loadFiles.js.map +1 -0
- package/packages/database/src/lib/loadMostRecentPreviousAnalysis.js.map +1 -0
- package/packages/database/src/lib/loadProject.js.map +1 -0
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +65 -0
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -0
- package/packages/database/src/lib/loadScenario.js.map +1 -0
- package/packages/database/src/lib/loadStatement.js.map +1 -0
- package/packages/database/src/lib/nullsToUndefines.js.map +1 -0
- package/packages/database/src/lib/projectToDb.js +18 -0
- package/packages/database/src/lib/projectToDb.js.map +1 -0
- package/packages/database/src/lib/saveBackgroundEvent.js.map +1 -0
- package/packages/database/src/lib/saveEntityStatements.js.map +1 -0
- package/packages/database/src/lib/saveFiles.js +33 -0
- package/packages/database/src/lib/saveFiles.js.map +1 -0
- package/packages/database/src/lib/saveStatement.js.map +1 -0
- package/packages/database/src/lib/scenarioToDb.js +18 -0
- package/packages/database/src/lib/scenarioToDb.js.map +1 -0
- package/packages/database/src/lib/supabase.js.map +1 -0
- package/packages/database/src/lib/updateBackgroundJobProgress.js.map +1 -0
- package/packages/database/src/lib/updateCommitMetadata.js +87 -0
- package/packages/database/src/lib/updateCommitMetadata.js.map +1 -0
- package/packages/database/src/lib/updateEntityBranch.js.map +1 -0
- package/packages/database/src/lib/updateFreshAnalysisMetadata.js.map +1 -0
- package/packages/database/src/lib/updateFreshAnalysisStatus.js +53 -0
- package/packages/database/src/lib/updateFreshAnalysisStatus.js.map +1 -0
- package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +81 -0
- package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -0
- package/packages/database/src/lib/updateProjectMetadata.js.map +1 -0
- package/packages/database/src/lib/upsertAnalyses.js.map +1 -0
- package/packages/database/src/lib/upsertAnalysesWithScenarios.js.map +1 -0
- package/packages/database/src/lib/upsertAnalysisBranches.js.map +1 -0
- package/packages/database/src/lib/upsertBackgroundJob.js.map +1 -0
- package/packages/database/src/lib/upsertBranches.js.map +1 -0
- package/packages/database/src/lib/upsertCommitBranches.js.map +1 -0
- package/packages/database/src/lib/upsertCommits.js.map +1 -0
- package/packages/database/src/lib/upsertEntities.js.map +1 -0
- package/packages/database/src/lib/upsertEntityBranches.js.map +1 -0
- package/packages/database/src/lib/upsertFiles.js.map +1 -0
- package/packages/database/src/lib/upsertGithubUser.js.map +1 -0
- package/packages/database/src/lib/upsertProjects.js.map +1 -0
- package/packages/database/src/lib/upsertScenarios.js.map +1 -0
- package/packages/generate/index.js +3 -0
- package/packages/generate/index.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +43 -21
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +217 -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 +41 -9
- package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
- package/packages/generate/src/lib/deepMerge.js +30 -2
- package/packages/generate/src/lib/deepMerge.js.map +1 -1
- package/packages/generate/src/lib/directExecutionScript.js +10 -1
- package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
- package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
- package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
- package/packages/generate/src/lib/scenarioComponent.js +5 -3
- package/packages/generate/src/lib/scenarioComponent.js.map +1 -1
- package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
- package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
- package/packages/github/src/lib/getCommitsFromGithub.js +1 -1
- package/packages/github/src/lib/loadOrCreateCommit.js +11 -1
- package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/packages/github/src/lib/syncHeadBranches.js +1 -1
- package/packages/github/src/lib/syncPrimaryBranch.js +4 -1
- package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/packages/github/src/lib/syncPullRequest.js +1 -1
- package/packages/github/src/lib/updateCommitBranchesInDb.js +1 -1
- package/packages/github/src/lib/updateFilesInDb.js +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/packages/process/src/ProcessManager.js +244 -0
- 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/types/src/enums/ProjectFramework.js +2 -0
- package/packages/types/src/enums/ProjectFramework.js.map +1 -1
- package/packages/utils/index.js +4 -0
- package/packages/utils/index.js.map +1 -1
- package/packages/utils/src/lib/Semaphore.js +40 -0
- package/packages/utils/src/lib/Semaphore.js.map +1 -0
- package/packages/utils/src/lib/applyUniversalMocks.js +65 -7
- package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/packages/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js +14 -2
- package/packages/utils/src/lib/frameworks/frameworkRouteFileNameToRoute.js.map +1 -1
- package/packages/utils/src/lib/frameworks/getNextRoutePath.js +2 -1
- package/packages/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
- package/packages/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
- package/packages/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
- package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +14 -2
- package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
- package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
- package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
- package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +62 -0
- package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
- package/packages/utils/src/lib/fs/rsyncCopy.js +120 -4
- package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
- package/packages/utils/src/lib/lightweightEntityExtractor.js +42 -0
- package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/packages/utils/src/lib/safeFileName.js +32 -3
- package/packages/utils/src/lib/safeFileName.js.map +1 -1
- package/packages/utils/src/lib/startCommand/buildStartCommand.js +45 -0
- package/packages/utils/src/lib/startCommand/buildStartCommand.js.map +1 -0
- package/packages/utils/src/lib/startCommand/getWebappInfo.js +67 -0
- package/packages/utils/src/lib/startCommand/getWebappInfo.js.map +1 -0
- package/packages/utils/src/lib/startCommand/index.js +3 -0
- package/packages/utils/src/lib/startCommand/index.js.map +1 -0
- package/scripts/npm-post-install.cjs +34 -0
- package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
- package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -149
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -235
- package/analyzer-template/packages/ai/src/lib/generateEntityDataMap.ts +0 -375
- package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -227
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -101
- package/analyzer-template/packages/github/dist/supabase/index.d.ts +0 -86
- package/analyzer-template/packages/github/dist/supabase/index.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/index.js +0 -84
- package/analyzer-template/packages/github/dist/supabase/index.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisBranchToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisBranchToDb.js +0 -19
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisBranchToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisToDb.js +0 -26
- package/analyzer-template/packages/github/dist/supabase/src/lib/analysisToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/backgroundJobToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/backgroundJobToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/branchToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/branchToDb.js +0 -18
- package/analyzer-template/packages/github/dist/supabase/src/lib/branchToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitBranchToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitBranchToDb.js +0 -13
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitBranchToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitToDb.js +0 -26
- package/analyzer-template/packages/github/dist/supabase/src/lib/commitToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createOrUpdateBranchCommitStats.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createOrUpdateBranchCommitStats.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createProject.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createProject.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createRetryFetch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/createRetryFetch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToAnalysis.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToAnalysis.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToAnalysisBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToAnalysisBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToBackgroundJob.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToBackgroundJob.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToCommit.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToCommit.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToCommitBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToCommitBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToEntity.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToEntity.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToEntityBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToEntityBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToFile.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToFile.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToProject.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToProject.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToScenario.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToScenario.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToScenarioComment.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToScenarioComment.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToUserScenario.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/dbToUserScenario.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteEntities.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteEntities.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteFile.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteFile.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteScenarios.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/deleteScenarios.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/entityToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/entityToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/fileToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/fileToDb.js +0 -14
- package/analyzer-template/packages/github/dist/supabase/src/lib/fileToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/generateSha.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/generateSha.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/jsonUpdateUtils.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/jsonUpdateUtils.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/aggregationHelpers.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/aggregationHelpers.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts +0 -67
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js +0 -360
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/schemaHelpers.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/schemaHelpers.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/sqliteBooleanPlugin.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/sqliteBooleanPlugin.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts +0 -87
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelationsTypes.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelationsTypes.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/analysesTable.d.ts +0 -105
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/analysesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/analysesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/analysisBranchesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/analysisBranchesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/backgroundJobsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/backgroundJobsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/branchesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/branchesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitBranchesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitBranchesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitsTable.d.ts +0 -47
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitsTable.js +0 -44
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/commitsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entitiesTable.d.ts +0 -65
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entitiesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entitiesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entityBranchesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entityBranchesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entityStatementsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/entityStatementsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/filesTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/filesTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/githubPayloadsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/githubPayloadsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/githubUsersTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/githubUsersTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/projectsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/projectsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/scenarioCommentsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/scenarioCommentsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/scenariosTable.d.ts +0 -65
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/scenariosTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/scenariosTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/statementsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/statementsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/teamsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/teamsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/userScenariosTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/userScenariosTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/userTeamsTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/userTeamsTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/usersTable.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/usersTable.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/upsertHelpers.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/upsertHelpers.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalyses.d.ts +0 -14
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalyses.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalyses.js +0 -131
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalyses.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalysis.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalysis.js +0 -130
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalysis.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalysisBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadAnalysisBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBackgroundJob.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBackgroundJob.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBranch.js +0 -90
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommit.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommit.js +0 -111
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommit.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommitBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommitBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommitMetadata.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommitMetadata.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommits.d.ts +0 -13
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommits.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommits.js +0 -188
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadCommits.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntities.d.ts +0 -11
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntities.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntities.js +0 -63
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntities.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntity.d.ts +0 -16
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntity.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntity.js +0 -72
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntity.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntityBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntityBranches.js +0 -114
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadEntityBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadFile.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadFile.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadFiles.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadFiles.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadMostRecentPreviousAnalysis.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadMostRecentPreviousAnalysis.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadProject.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadProject.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadReadyToBeCapturedAnalyses.js +0 -50
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadReadyToBeCapturedAnalyses.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadScenario.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadScenario.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadStatement.d.ts +0 -3
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadStatement.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/loadStatement.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/nullsToUndefines.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/nullsToUndefines.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/projectToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/projectToDb.js +0 -18
- package/analyzer-template/packages/github/dist/supabase/src/lib/projectToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveBackgroundEvent.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveBackgroundEvent.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveEntityStatements.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveEntityStatements.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveFiles.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveFiles.js +0 -33
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveFiles.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveStatement.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/saveStatement.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/scenarioToDb.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/scenarioToDb.js +0 -18
- package/analyzer-template/packages/github/dist/supabase/src/lib/scenarioToDb.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/supabase.d.ts +0 -4
- package/analyzer-template/packages/github/dist/supabase/src/lib/supabase.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/supabase.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateBackgroundJobProgress.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateBackgroundJobProgress.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateCommitMetadata.d.ts +0 -13
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateCommitMetadata.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateCommitMetadata.js +0 -100
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateCommitMetadata.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateEntityBranch.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateEntityBranch.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisMetadata.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisMetadata.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatus.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatus.js +0 -42
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatus.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.js +0 -70
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateProjectMetadata.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/updateProjectMetadata.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalyses.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalyses.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalysesWithScenarios.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalysesWithScenarios.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalysisBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertAnalysisBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertBackgroundJob.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertBackgroundJob.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertCommitBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertCommitBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertCommits.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertCommits.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertEntities.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertEntities.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertEntityBranches.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertEntityBranches.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertFiles.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertFiles.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertGithubUser.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertGithubUser.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertProjects.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertProjects.js.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertScenarios.d.ts.map +0 -1
- package/analyzer-template/packages/github/dist/supabase/src/lib/upsertScenarios.js.map +0 -1
- package/analyzer-template/packages/supabase/client.ts +0 -35
- package/analyzer-template/packages/supabase/index.ts +0 -93
- package/analyzer-template/packages/supabase/package.json +0 -31
- package/analyzer-template/packages/supabase/src/lib/analysisBranchToDb.ts +0 -28
- package/analyzer-template/packages/supabase/src/lib/analysisToDb.ts +0 -59
- package/analyzer-template/packages/supabase/src/lib/branchToDb.ts +0 -24
- package/analyzer-template/packages/supabase/src/lib/commitBranchToDb.ts +0 -20
- package/analyzer-template/packages/supabase/src/lib/commitToDb.ts +0 -47
- package/analyzer-template/packages/supabase/src/lib/fileToDb.ts +0 -17
- package/analyzer-template/packages/supabase/src/lib/kysely/db.ts +0 -476
- package/analyzer-template/packages/supabase/src/lib/kysely/tableRelations.ts +0 -105
- package/analyzer-template/packages/supabase/src/lib/kysely/tables/commitsTable.ts +0 -61
- package/analyzer-template/packages/supabase/src/lib/loadAnalyses.ts +0 -218
- package/analyzer-template/packages/supabase/src/lib/loadAnalysis.ts +0 -210
- package/analyzer-template/packages/supabase/src/lib/loadBranch.ts +0 -122
- package/analyzer-template/packages/supabase/src/lib/loadCommit.ts +0 -163
- package/analyzer-template/packages/supabase/src/lib/loadCommits.ts +0 -251
- package/analyzer-template/packages/supabase/src/lib/loadEntities.ts +0 -94
- package/analyzer-template/packages/supabase/src/lib/loadEntity.ts +0 -110
- package/analyzer-template/packages/supabase/src/lib/loadEntityBranches.ts +0 -166
- package/analyzer-template/packages/supabase/src/lib/loadFile.ts +0 -47
- package/analyzer-template/packages/supabase/src/lib/loadFiles.ts +0 -137
- package/analyzer-template/packages/supabase/src/lib/loadReadyToBeCapturedAnalyses.ts +0 -76
- package/analyzer-template/packages/supabase/src/lib/loadStatement.ts +0 -23
- package/analyzer-template/packages/supabase/src/lib/projectToDb.ts +0 -35
- package/analyzer-template/packages/supabase/src/lib/saveEntityStatements.ts +0 -28
- package/analyzer-template/packages/supabase/src/lib/saveFiles.ts +0 -43
- package/analyzer-template/packages/supabase/src/lib/scenarioToDb.ts +0 -34
- package/analyzer-template/packages/supabase/src/lib/updateCommitMetadata.ts +0 -188
- package/analyzer-template/packages/supabase/src/lib/updateFreshAnalysisStatus.ts +0 -64
- package/analyzer-template/packages/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.ts +0 -94
- package/analyzer-template/packages/supabase/src/lib/updateProjectMetadata.ts +0 -96
- package/analyzer-template/packages/supabase/src/lib/userScenarioToDb.ts +0 -18
- 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 +0 -244
- 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/commands/detect-universal-mocks.js +0 -118
- package/codeyam-cli/src/commands/detect-universal-mocks.js.map +0 -1
- package/codeyam-cli/src/commands/list.js +0 -31
- package/codeyam-cli/src/commands/list.js.map +0 -1
- package/codeyam-cli/src/utils/universal-mocks.js +0 -152
- package/codeyam-cli/src/utils/universal-mocks.js.map +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-rqv54FUY.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-B0oiPem-.js +0 -26
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DqXXjAJ7.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-BKKG1s2B.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DU_jxCPD.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-5DY-YIxu.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-DmjXUj6m.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/_index-DvSrcxsk.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CsaMd9mb.js +0 -10
- package/codeyam-cli/src/webserver/build/client/assets/chart-column-VXBS6qOn.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/circle-alert-n5GUC2AS.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/clock-DKqtX8js.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/components-Dj-Ggnl2.js +0 -40
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-C1gnJVOL.svg +0 -4
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BbR3FwNc.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-BHiWkb_W.js +0 -11
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-L7M9Vr5z.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-C9w-q7P3.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/entityVersioning-Bk_YB1jM.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-CdGoUs8A.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/file-text-B6Er7j5k.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/files-KcDVw1FY.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-B9uZ8eSJ.js +0 -12
- package/codeyam-cli/src/webserver/build/client/assets/globals-B0f88RTV.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-v3c6DFp4.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-fca08d7e.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/root-Cf8VBqIb.js +0 -16
- package/codeyam-cli/src/webserver/build/client/assets/search-DA14wXpu.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-COJUrwGu.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/settings-NU_ZquhK.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/simulations-CNaMJ-nR.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-Lumm1t01.js +0 -2
- package/codeyam-cli/src/webserver/build/client/assets/useToast-BRShB17p.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/zap-BvukH0eN.js +0 -1
- package/codeyam-cli/src/webserver/build/client/cy-logo-cli.svg +0 -13
- package/codeyam-cli/src/webserver/build/client/favicon.svg +0 -13
- package/codeyam-cli/src/webserver/build/server/assets/index-DHr4rT4u.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-Bi1mj14J.js +0 -166
- package/codeyam-cli/src/webserver/public/cy-logo-cli.svg +0 -13
- package/codeyam-cli/src/webserver/public/favicon.svg +0 -13
- package/codeyam-cli/templates/codeyam-debug-skill.md +0 -557
- package/codeyam-cli/templates/codeyam-setup-skill.md +0 -468
- package/codeyam-cli/templates/codeyam-sim-skill.md +0 -222
- package/codeyam-cli/templates/codeyam-stop-hook.sh +0 -284
- package/codeyam-cli/templates/codeyam-test-skill.md +0 -178
- package/codeyam-cli/templates/codeyam-verify-skill.md +0 -179
- 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 -112
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -190
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateEntityDataMap.js +0 -335
- package/packages/ai/src/lib/generateEntityDataMap.js.map +0 -1
- package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -182
- 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/generateEntityDataMapGenerator.js +0 -17
- package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.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 -59
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
- package/packages/supabase/index.js +0 -84
- package/packages/supabase/index.js.map +0 -1
- package/packages/supabase/src/lib/analysisBranchToDb.js +0 -19
- package/packages/supabase/src/lib/analysisBranchToDb.js.map +0 -1
- package/packages/supabase/src/lib/analysisToDb.js +0 -26
- package/packages/supabase/src/lib/analysisToDb.js.map +0 -1
- package/packages/supabase/src/lib/backgroundJobToDb.js.map +0 -1
- package/packages/supabase/src/lib/branchToDb.js +0 -18
- package/packages/supabase/src/lib/branchToDb.js.map +0 -1
- package/packages/supabase/src/lib/commitBranchToDb.js +0 -13
- package/packages/supabase/src/lib/commitBranchToDb.js.map +0 -1
- package/packages/supabase/src/lib/commitToDb.js +0 -26
- package/packages/supabase/src/lib/commitToDb.js.map +0 -1
- package/packages/supabase/src/lib/createOrUpdateBranchCommitStats.js.map +0 -1
- package/packages/supabase/src/lib/createProject.js.map +0 -1
- package/packages/supabase/src/lib/createRetryFetch.js.map +0 -1
- package/packages/supabase/src/lib/dbToAnalysis.js.map +0 -1
- package/packages/supabase/src/lib/dbToAnalysisBranch.js.map +0 -1
- package/packages/supabase/src/lib/dbToBackgroundJob.js.map +0 -1
- package/packages/supabase/src/lib/dbToBranch.js.map +0 -1
- package/packages/supabase/src/lib/dbToCommit.js.map +0 -1
- package/packages/supabase/src/lib/dbToCommitBranch.js.map +0 -1
- package/packages/supabase/src/lib/dbToEntity.js.map +0 -1
- package/packages/supabase/src/lib/dbToEntityBranch.js.map +0 -1
- package/packages/supabase/src/lib/dbToFile.js.map +0 -1
- package/packages/supabase/src/lib/dbToProject.js.map +0 -1
- package/packages/supabase/src/lib/dbToScenario.js.map +0 -1
- package/packages/supabase/src/lib/dbToScenarioComment.js.map +0 -1
- package/packages/supabase/src/lib/dbToUserScenario.js.map +0 -1
- package/packages/supabase/src/lib/deleteBranch.js.map +0 -1
- package/packages/supabase/src/lib/deleteEntities.js.map +0 -1
- package/packages/supabase/src/lib/deleteFile.js.map +0 -1
- package/packages/supabase/src/lib/deleteScenarios.js.map +0 -1
- package/packages/supabase/src/lib/entityToDb.js.map +0 -1
- package/packages/supabase/src/lib/fileToDb.js +0 -14
- package/packages/supabase/src/lib/fileToDb.js.map +0 -1
- package/packages/supabase/src/lib/generateSha.js.map +0 -1
- package/packages/supabase/src/lib/jsonUpdateUtils.js.map +0 -1
- package/packages/supabase/src/lib/kysely/aggregationHelpers.js.map +0 -1
- package/packages/supabase/src/lib/kysely/db.js +0 -360
- package/packages/supabase/src/lib/kysely/db.js.map +0 -1
- package/packages/supabase/src/lib/kysely/schemaHelpers.js.map +0 -1
- package/packages/supabase/src/lib/kysely/sqliteBooleanPlugin.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tableRelations.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tableRelationsTypes.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/analysesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/analysisBranchesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/backgroundJobsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/branchesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/commitBranchesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/commitsTable.js +0 -44
- package/packages/supabase/src/lib/kysely/tables/commitsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/entitiesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/entityBranchesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/entityStatementsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/filesTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/githubPayloadsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/githubUsersTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/projectsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/scenarioCommentsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/scenariosTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/statementsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/teamsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/userScenariosTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/userTeamsTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/tables/usersTable.js.map +0 -1
- package/packages/supabase/src/lib/kysely/upsertHelpers.js.map +0 -1
- package/packages/supabase/src/lib/loadAnalyses.js +0 -131
- package/packages/supabase/src/lib/loadAnalyses.js.map +0 -1
- package/packages/supabase/src/lib/loadAnalysis.js +0 -130
- package/packages/supabase/src/lib/loadAnalysis.js.map +0 -1
- package/packages/supabase/src/lib/loadAnalysisBranches.js.map +0 -1
- package/packages/supabase/src/lib/loadBackgroundJob.js.map +0 -1
- package/packages/supabase/src/lib/loadBranch.js +0 -90
- package/packages/supabase/src/lib/loadBranch.js.map +0 -1
- package/packages/supabase/src/lib/loadBranches.js.map +0 -1
- package/packages/supabase/src/lib/loadCommit.js +0 -111
- package/packages/supabase/src/lib/loadCommit.js.map +0 -1
- package/packages/supabase/src/lib/loadCommitBranches.js.map +0 -1
- package/packages/supabase/src/lib/loadCommitMetadata.js.map +0 -1
- package/packages/supabase/src/lib/loadCommits.js +0 -188
- package/packages/supabase/src/lib/loadCommits.js.map +0 -1
- package/packages/supabase/src/lib/loadEntities.js +0 -63
- package/packages/supabase/src/lib/loadEntities.js.map +0 -1
- package/packages/supabase/src/lib/loadEntity.js +0 -72
- package/packages/supabase/src/lib/loadEntity.js.map +0 -1
- package/packages/supabase/src/lib/loadEntityBranches.js +0 -114
- package/packages/supabase/src/lib/loadEntityBranches.js.map +0 -1
- package/packages/supabase/src/lib/loadFile.js.map +0 -1
- package/packages/supabase/src/lib/loadFiles.js.map +0 -1
- package/packages/supabase/src/lib/loadMostRecentPreviousAnalysis.js.map +0 -1
- package/packages/supabase/src/lib/loadProject.js.map +0 -1
- package/packages/supabase/src/lib/loadReadyToBeCapturedAnalyses.js +0 -50
- package/packages/supabase/src/lib/loadReadyToBeCapturedAnalyses.js.map +0 -1
- package/packages/supabase/src/lib/loadScenario.js.map +0 -1
- package/packages/supabase/src/lib/loadStatement.js.map +0 -1
- package/packages/supabase/src/lib/nullsToUndefines.js.map +0 -1
- package/packages/supabase/src/lib/projectToDb.js +0 -18
- package/packages/supabase/src/lib/projectToDb.js.map +0 -1
- package/packages/supabase/src/lib/saveBackgroundEvent.js.map +0 -1
- package/packages/supabase/src/lib/saveEntityStatements.js.map +0 -1
- package/packages/supabase/src/lib/saveFiles.js +0 -33
- package/packages/supabase/src/lib/saveFiles.js.map +0 -1
- package/packages/supabase/src/lib/saveStatement.js.map +0 -1
- package/packages/supabase/src/lib/scenarioToDb.js +0 -18
- package/packages/supabase/src/lib/scenarioToDb.js.map +0 -1
- package/packages/supabase/src/lib/supabase.js.map +0 -1
- package/packages/supabase/src/lib/updateBackgroundJobProgress.js.map +0 -1
- package/packages/supabase/src/lib/updateCommitMetadata.js +0 -100
- package/packages/supabase/src/lib/updateCommitMetadata.js.map +0 -1
- package/packages/supabase/src/lib/updateEntityBranch.js.map +0 -1
- package/packages/supabase/src/lib/updateFreshAnalysisMetadata.js.map +0 -1
- package/packages/supabase/src/lib/updateFreshAnalysisStatus.js +0 -42
- package/packages/supabase/src/lib/updateFreshAnalysisStatus.js.map +0 -1
- package/packages/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.js +0 -70
- package/packages/supabase/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +0 -1
- package/packages/supabase/src/lib/updateProjectMetadata.js.map +0 -1
- package/packages/supabase/src/lib/upsertAnalyses.js.map +0 -1
- package/packages/supabase/src/lib/upsertAnalysesWithScenarios.js.map +0 -1
- package/packages/supabase/src/lib/upsertAnalysisBranches.js.map +0 -1
- package/packages/supabase/src/lib/upsertBackgroundJob.js.map +0 -1
- package/packages/supabase/src/lib/upsertBranches.js.map +0 -1
- package/packages/supabase/src/lib/upsertCommitBranches.js.map +0 -1
- package/packages/supabase/src/lib/upsertCommits.js.map +0 -1
- package/packages/supabase/src/lib/upsertEntities.js.map +0 -1
- package/packages/supabase/src/lib/upsertEntityBranches.js.map +0 -1
- package/packages/supabase/src/lib/upsertFiles.js.map +0 -1
- package/packages/supabase/src/lib/upsertGithubUser.js.map +0 -1
- package/packages/supabase/src/lib/upsertProjects.js.map +0 -1
- package/packages/supabase/src/lib/upsertScenarios.js.map +0 -1
- package/scripts/finalize-analyzer.cjs +0 -79
- /package/analyzer-template/packages/{supabase → database}/__mocks__/index.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/backgroundJobToDb.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/listenForCommits_Client.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/loadAnalysesInClient.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/loadAnalysis_Client.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/loadBranches_Client.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/loadCommit_Client.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/client/upsertFiles_Client.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/createOrUpdateBranchCommitStats.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/createProject.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/createRetryFetch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToAnalysis.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToAnalysisBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToBackgroundJob.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToCommit.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToCommitBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToEntity.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToEntityBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToFile.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToProject.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToScenario.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToScenarioComment.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/dbToUserScenario.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/deleteBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/deleteEntities.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/deleteFile.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/deleteScenarios.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/entityToDb.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/generateSha.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/jsonUpdateUtils.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/aggregationHelpers.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/schemaHelpers.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/sqliteBooleanPlugin.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tableRelationsTypes.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/analysesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/analysisBranchesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/backgroundJobsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/branchesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/commitBranchesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/entitiesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/entityBranchesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/entityStatementsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/filesTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/githubPayloadsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/githubUsersTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/projectsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/scenarioCommentsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/scenariosTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/statementsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/teamsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/userScenariosTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/userTeamsTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/tables/usersTable.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely/upsertHelpers.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/kysely.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadAnalysisBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadBackgroundJob.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadCommitBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadCommitMetadata.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadMostRecentPreviousAnalysis.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadProject.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/loadScenario.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/nullsToUndefines.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/saveBackgroundEvent.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/saveStatement.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/scenarioCommentToDb.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/supabase.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/updateBackgroundJobProgress.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/updateEntityBranch.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/updateFreshAnalysisMetadata.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertAnalyses.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertAnalysesWithScenarios.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertAnalysisBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertBackgroundJob.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertCommitBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertCommits.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertEntities.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertEntityBranches.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertFiles.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertGithubUser.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertProjects.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/src/lib/upsertScenarios.ts +0 -0
- /package/analyzer-template/packages/{supabase → database}/tsconfig.json +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/analysisBranchToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/analysisToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/backgroundJobToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/backgroundJobToDb.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/branchToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/commitBranchToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/commitToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createOrUpdateBranchCommitStats.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createOrUpdateBranchCommitStats.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createProject.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createProject.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createRetryFetch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/createRetryFetch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToAnalysis.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToAnalysis.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToAnalysisBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToAnalysisBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToBackgroundJob.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToBackgroundJob.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToCommit.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToCommit.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToCommitBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToCommitBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToEntity.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToEntity.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToEntityBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToEntityBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToFile.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToFile.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToProject.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToProject.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToScenario.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToScenario.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToScenarioComment.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToScenarioComment.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToUserScenario.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/dbToUserScenario.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteEntities.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteEntities.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteFile.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteFile.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteScenarios.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/deleteScenarios.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/entityToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/entityToDb.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/fileToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/generateSha.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/generateSha.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/jsonUpdateUtils.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/jsonUpdateUtils.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/aggregationHelpers.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/aggregationHelpers.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/schemaHelpers.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/schemaHelpers.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/sqliteBooleanPlugin.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/sqliteBooleanPlugin.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tableRelations.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tableRelationsTypes.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tableRelationsTypes.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/analysesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/analysisBranchesTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/analysisBranchesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/backgroundJobsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/backgroundJobsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/branchesTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/branchesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/commitBranchesTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/commitBranchesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/entitiesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/entityBranchesTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/entityBranchesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/entityStatementsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/entityStatementsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/filesTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/filesTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/githubPayloadsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/githubPayloadsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/githubUsersTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/githubUsersTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/projectsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/projectsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/scenarioCommentsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/scenarioCommentsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/scenariosTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/statementsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/statementsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/teamsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/teamsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/userScenariosTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/userScenariosTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/userTeamsTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/userTeamsTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/usersTable.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/tables/usersTable.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/upsertHelpers.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/kysely/upsertHelpers.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadAnalysis.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadAnalysisBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadAnalysisBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadBackgroundJob.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadBackgroundJob.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadCommit.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadCommitBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadCommitBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadCommitMetadata.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadCommitMetadata.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadEntityBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadFile.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadFile.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadFiles.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadFiles.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadMostRecentPreviousAnalysis.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadMostRecentPreviousAnalysis.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadProject.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadProject.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadReadyToBeCapturedAnalyses.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadScenario.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadScenario.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/loadStatement.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/nullsToUndefines.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/nullsToUndefines.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/projectToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveBackgroundEvent.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveBackgroundEvent.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveEntityStatements.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveEntityStatements.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveFiles.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveStatement.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/saveStatement.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/scenarioToDb.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/supabase.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateBackgroundJobProgress.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateBackgroundJobProgress.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateEntityBranch.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateEntityBranch.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateFreshAnalysisMetadata.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateFreshAnalysisMetadata.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateFreshAnalysisStatus.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateProjectMetadata.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/updateProjectMetadata.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalyses.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalyses.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalysesWithScenarios.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalysesWithScenarios.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalysisBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertAnalysisBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertBackgroundJob.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertBackgroundJob.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertCommitBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertCommitBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertCommits.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertCommits.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertEntities.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertEntities.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertEntityBranches.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertEntityBranches.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertFiles.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertFiles.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertGithubUser.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertGithubUser.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertProjects.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertProjects.js +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertScenarios.d.ts +0 -0
- /package/analyzer-template/packages/github/dist/{supabase → database}/src/lib/upsertScenarios.js +0 -0
- /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/packages/{supabase → database}/src/lib/backgroundJobToDb.js +0 -0
- /package/packages/{supabase → database}/src/lib/createOrUpdateBranchCommitStats.js +0 -0
- /package/packages/{supabase → database}/src/lib/createProject.js +0 -0
- /package/packages/{supabase → database}/src/lib/createRetryFetch.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToAnalysis.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToAnalysisBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToBackgroundJob.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToCommit.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToCommitBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToEntity.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToEntityBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToFile.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToProject.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToScenario.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToScenarioComment.js +0 -0
- /package/packages/{supabase → database}/src/lib/dbToUserScenario.js +0 -0
- /package/packages/{supabase → database}/src/lib/deleteBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/deleteEntities.js +0 -0
- /package/packages/{supabase → database}/src/lib/deleteFile.js +0 -0
- /package/packages/{supabase → database}/src/lib/deleteScenarios.js +0 -0
- /package/packages/{supabase → database}/src/lib/entityToDb.js +0 -0
- /package/packages/{supabase → database}/src/lib/generateSha.js +0 -0
- /package/packages/{supabase → database}/src/lib/jsonUpdateUtils.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/aggregationHelpers.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/schemaHelpers.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/sqliteBooleanPlugin.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tableRelations.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tableRelationsTypes.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/analysesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/analysisBranchesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/backgroundJobsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/branchesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/commitBranchesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/entitiesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/entityBranchesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/entityStatementsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/filesTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/githubPayloadsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/githubUsersTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/projectsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/scenarioCommentsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/scenariosTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/statementsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/teamsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/userScenariosTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/userTeamsTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/tables/usersTable.js +0 -0
- /package/packages/{supabase → database}/src/lib/kysely/upsertHelpers.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadAnalysisBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadBackgroundJob.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadCommitBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadCommitMetadata.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadFile.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadFiles.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadMostRecentPreviousAnalysis.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadProject.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadScenario.js +0 -0
- /package/packages/{supabase → database}/src/lib/loadStatement.js +0 -0
- /package/packages/{supabase → database}/src/lib/nullsToUndefines.js +0 -0
- /package/packages/{supabase → database}/src/lib/saveBackgroundEvent.js +0 -0
- /package/packages/{supabase → database}/src/lib/saveEntityStatements.js +0 -0
- /package/packages/{supabase → database}/src/lib/saveStatement.js +0 -0
- /package/packages/{supabase → database}/src/lib/supabase.js +0 -0
- /package/packages/{supabase → database}/src/lib/updateBackgroundJobProgress.js +0 -0
- /package/packages/{supabase → database}/src/lib/updateEntityBranch.js +0 -0
- /package/packages/{supabase → database}/src/lib/updateFreshAnalysisMetadata.js +0 -0
- /package/packages/{supabase → database}/src/lib/updateProjectMetadata.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertAnalyses.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertAnalysesWithScenarios.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertAnalysisBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertBackgroundJob.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertCommitBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertCommits.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertEntities.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertEntityBranches.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertFiles.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertGithubUser.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertProjects.js +0 -0
- /package/packages/{supabase → database}/src/lib/upsertScenarios.js +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,765 @@
|
|
|
1
|
+
var Nh=Object.defineProperty;var jl=e=>{throw TypeError(e)};var Sh=(e,t,r)=>t in e?Nh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var vt=(e,t,r)=>Sh(e,typeof t!="symbol"?t+"":t,r),Ch=(e,t,r)=>t.has(e)||jl("Cannot "+r);var Pl=(e,t,r)=>(Ch(e,t,"read from private field"),r?r.call(e):t.get(e)),Al=(e,t,r)=>t.has(e)?jl("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 d,Fragment as ve}from"react/jsx-runtime";import{PassThrough as kh}from"node:stream";import{createReadableStreamFromReadable as Eh}from"@react-router/node";import{ServerRouter as _h,useFetcher as Ke,useLocation as Vr,useNavigate as zt,Link as ke,UNSAFE_withComponentProps as nt,Meta as jh,Links as Ph,ScrollRestoration as Ah,Scripts as Th,UNSAFE_withErrorBoundaryProps as Mh,useRouteError as $h,isRouteErrorResponse as qo,useLoaderData as lt,useRevalidator as Bt,Outlet as Sd,data as le,useSearchParams as lr,useRouteLoaderData as Cd,useParams as kd,useActionData as Fh,redirect as Rh}from"react-router";import{isbot as Dh}from"isbot";import{renderToPipeableStream as Ih}from"react-dom/server";import{useState as P,useEffect as se,useCallback as ce,createContext as Ga,useContext as ao,useRef as ye,useMemo as pe,forwardRef as Oh,useImperativeHandle as Lh,Component as zh}from"react";import{Settings as Tl,CheckCircle2 as qa,Bug as Ed,AlertTriangle as Ws,Check as Mt,Copy as Ot,Loader2 as It,PencilRuler as Bh,HomeIcon as Yh,GitCommitIcon as Ml,File as Uh,RefreshCw as Wh,BookOpen as Js,FlaskConical as Jh,SettingsIcon as Hh,PanelsTopLeftIcon as Vh,ComponentIcon as Kh,FileText as $l,Code as Fl,Box as Gh,List as qh,BarChart3 as Qh,Tag as Zh,Image as Br,Code2 as _d,Activity as Qo,ChevronDown as At,CircleEqual as Xh,ArrowLeft as em,Terminal as Hs,Search as Kr,ChevronLeft as tm,ChevronRight as yn,Save as nm,MessageSquare as rm,Pause as jd,ListTodo as sm,PauseCircle as om,FileCode as Vs,GripVertical as am,Ban as im,CheckCircle as lm,FolderOpen as cm,CodeXml as dm,Zap as um,Pencil as pm,Trash2 as hm,X as cr,Folder as Pd,Info as _a,Plus as Qa,Eye as mm,FolderTree as fm,ChevronsUpDown as Ad,ChevronsDownUp as Td}from"lucide-react";import"fetch-retry";import gm from"better-sqlite3";import{Pool as ym}from"pg";import*as q from"fs";import de,{existsSync as Pt,readdirSync as xm,rmSync as Zo,readFileSync as Rl}from"fs";import*as G from"path";import ee,{join as Yr}from"path";import{OperationNodeTransformer as bm,sql as wt,Kysely as Md,ParseJSONResultsPlugin as vm,SqliteDialect as wm,PostgresDialect as Nm}from"kysely";import*as Sm from"kysely/helpers/sqlite";import*as Cm from"kysely/helpers/postgres";import et from"typescript";import*as Pe from"fs/promises";import Ae,{writeFile as Rr,readFile as ja,mkdir as km}from"fs/promises";import*as io from"os";import Pa,{homedir as Em}from"os";import _m from"prompts";import Ks from"chalk";import*as Za from"crypto";import dr,{randomUUID as Xa,createHmac as jm}from"crypto";import{execSync as Me,spawn as kt,exec as ei}from"child_process";import{fileURLToPath as lo}from"url";import{promisify as ti}from"util";import Pm from"dotenv";import Am,{EventEmitter as Gr}from"events";import{v4 as Tm}from"uuid";import ni from"http";import $d from"net";import{WebSocket as ri}from"ws";import"node-pty";import Mm from"openai";import $m from"p-queue";import Dl from"p-retry";import{DynamoDBClient as co,PutItemCommand as Fm}from"@aws-sdk/client-dynamodb";import{LRUCache as si}from"lru-cache";import"pluralize";import"piscina";import Rm from"json5";import{marshall as Dm}from"@aws-sdk/util-dynamodb";import Im from"v8";import{Prism as Om}from"react-syntax-highlighter";import{vscDarkPlus as Lm}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as zm}from"node:crypto";import{minimatch as Aa}from"minimatch";import Bm from"react-markdown";import Ym from"remark-gfm";import Um from"react-diff-viewer-continued";const Fd=5e3;function Wm(e,t,r,s,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((a,i)=>{let l=!1,c=e.headers.get("user-agent"),u=c&&Dh(c)||s.isSpaMode?"onAllReady":"onShellReady",p=setTimeout(()=>m(),Fd+1e3);const{pipe:h,abort:m}=Ih(n(_h,{context:s,url:e.url}),{[u](){l=!0;const f=new kh({final(g){clearTimeout(p),p=void 0,g()}}),y=Eh(f);r.set("Content-Type","text/html"),h(f),a(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const Jm=Object.freeze(Object.defineProperty({__proto__:null,default:Wm,streamTimeout:Fd},Symbol.toStringTag,{value:"Module"})),Hm=2e3,Vm=5e3;function Km(e){return e.startsWith("/editor")?Vm:Hm}function Gm(e){const{now:t,lastRevalidation:r,throttleMs:s}=e;if(r===0)return"immediate";const o=t-r;return o>=s?"immediate":{action:"deferred",delayMs:s-o}}function qm({id:e,selected:t,onClick:r,icon:s,name:o}){const[a,i]=P(!1);se(()=>{i(!0)},[]);const l=ce(()=>{r==null||r(e)},[r,e]);return d("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:a&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:o})]})}const uo="/assets/cy-logo-cli-DoA97ML3.svg";function Qm(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 Zm({content:e,className:t=""}){const[r,s]=P(!1),o=ce(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(a=>{console.error("Failed to copy:",a)})},[e]);return n("button",{onClick:o,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?d(ve,{children:[n(Mt,{size:14}),"Copied"]}):d(ve,{children:[n(Ot,{size:14}),"Copy"]})})}function Rd({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:o}){const[a,i]=P(""),[l,c]=P(s),[u,p]=P(!1),[h,m]=P(!1),[f,y]=P(null),[g,x]=P(null),b=Ke(),v=b.state!=="idle",N=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",C=()=>{const _=`/codeyam-diagnose ${w}`;return a.trim()?`${_} ${a.trim()}`:_};if(b.data&&!h&&!g){const _=b.data;_.success&&_.reportId?(m(!0),y(_.reportId)):_.error&&x(_.error)}const S=async()=>{x(null);const _=new FormData;if(_.append("issueType","other"),_.append("description",a),_.append("email",l),_.append("source",r.source),_.append("entitySha",r.entitySha||""),_.append("scenarioId",r.scenarioId||""),_.append("analysisId",r.analysisId||""),_.append("currentUrl",r.currentUrl),_.append("entityName",r.entityName||""),_.append("entityType",r.entityType||""),_.append("scenarioName",r.scenarioName||""),_.append("errorMessage",r.errorMessage||""),o)try{const M=await(await fetch(o)).blob();_.append("screenshot",M,"screenshot.jpg")}catch($){console.error("Failed to convert screenshot:",$)}b.submit(_,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),p(!1),m(!1),y(null),x(null),t()},T=_=>{_.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:T,children:d("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[d("div",{className:"flex items-center justify-between mb-6",children:[d("div",{className:"flex items-center gap-3",children:[v?n("div",{className:"animate-spin",children:n(Tl,{size:24,style:{strokeWidth:1.5}})}):h?n(qa,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Ed,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick: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"})})})]}),h?d("div",{children:[d("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!"}),d("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"})})]}):d("div",{children:[d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[d("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:Qm(r)}),n("button",{type:"button",onClick:()=>p(!u),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:u?"Hide":"Details"})]}),u&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),o&&d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),d("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:a,onChange:_=>i(_.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),N&&d(ve,{children:[d("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[d("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."}),d("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:C()}),n(Zm,{content:C(),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"})]})]}),d("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"})})]})]}),d("div",{className:N?"opacity-75":"",children:[N&&d("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)"})]}),d("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:_=>c(_.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]"})]}),d("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Ws,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),d("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),v&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),g&&d("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Ws,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),d("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:k,disabled:v,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void S(),disabled:v,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:v?d(ve,{children:[n("div",{className:"animate-spin",children:n(Tl,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Il={source:"navbar"},oi=Ga(void 0);function Xm({children:e}){const[t,r]=P(Il),s=ce(a=>{r(a)},[]),o=ce(()=>{r(Il)},[]);return n(oi.Provider,{value:{contextData:t,setContextData:s,resetContextData:o},children:e})}function Yt(e){const t=ao(oi),r=ye(t);se(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function ef(){const e=ao(oi),t=Vr();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 tf({labs:e,isAdmin:t,editorMode:r}){var S;const s=Vr(),o=zt(),[a,i]=P(),[l,c]=P(!1),[u,p]=P(!1),[h,m]=P(null),f=Ke();se(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((S=f.data)==null?void 0:S.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,b=[{id:"editor",icon:n(Bh,{style:g}),link:"/editor",name:"Editor",hidden:!r,newTab:!0},{id:"dashboard",icon:n(Yh,{style:g}),link:"/",name:"Dashboard",hidden:!x||r},{id:"simulations",icon:d("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,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:!x||r},{id:"git",icon:n(Ml,{style:g}),link:"/git",name:"Git",hidden:!x||r},{id:"files",icon:n(Uh,{style:g}),link:"/files",name:"Files",hidden:!x||r},{id:"activity",icon:n(Wh,{style:g}),link:"/activity",name:"Activity",hidden:!x||r},{id:"memory",icon:n(Js,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Jh,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Hh,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ml,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Vh,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Kh,{style:g}),link:"/components",name:"Components",hidden:!0}],v=ce(k=>{const T=b.find(_=>_.id===k);T!=null&&T.link&&(T.newTab?window.open(T.link,"_blank"):o(T.link)),i(_=>_===k?void 0:k)},[b,o]);se(()=>{const k={editor:["editor"],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[T,_]of Object.entries(k))if(_.some($=>$==="/"?s.pathname==="/":s.pathname.includes($))){i(T);return}i(void 0)},[s]);const N=async()=>{p(!0);try{const{default:k}=await import("html2canvas-pro"),_=(await k(document.body)).toDataURL("image/jpeg",.8);m(_),c(!0)}catch(k){console.error("Screenshot capture failed:",k),c(!0)}finally{p(!1)}},w=()=>{c(!1),m(null)},C=ef();return d(ve,{children:[d("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[d("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(ke,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:uo,alt:"CodeYam",className:"h-6"})})}),b.filter(k=>!k.hidden).map(k=>n(qm,{id:k.id,selected:k.id===a,onClick:v,icon:k.icon,name:k.name},`sidebar-button-${k.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void N(),disabled:u,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:u?n(It,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Ed,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:u?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),l&&n(Rd,{isOpen:!0,onClose:w,context:C,defaultEmail:y,screenshotDataUrl:h??void 0})]})}const Dd=Ga(void 0);function nf({children:e}){const[t,r]=P([]),s=ce((a,i="info",l=5e3)=>{const u={id:`toast-${Date.now()}-${Math.random()}`,message:a,type:i,duration:l};r(p=>[...p,u])},[]),o=ce(a=>{r(i=>i.filter(l=>l.id!==a))},[]);return n(Dd.Provider,{value:{toasts:t,showToast:s,closeToast:o},children:e})}function ai(){const e=ao(Dd);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function rf({toast:e,onClose:t}){se(()=>{const o=e.duration||5e3;if(o>0){const a=setTimeout(()=>{t(e.id)},o);return()=>clearTimeout(a)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return d("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 sf({toasts:e,onClose:t}){return e.length===0?null:d("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(rf,{toast:r,onClose:t},r.id))]})}function Qt(e,t){const[r,s]=P(""),[o,a]=P(!1),[i,l]=P(null),[c,u]=P(null),[p,h]=P(!1);se(()=>{t&&(h(!1),a(!1),l(null),u(null))},[t]),se(()=>{if(!e||!t){t||s("");return}const f=async()=>{if(!p)try{const g=await fetch(`/api/logs/${e}`);if(g.ok){const b=(await g.text()).trim().split(`
|
|
18
|
+
`).filter(C=>C.length>0);if(b.length<3){a(!1),h(!1),l(null),u(null),s("");return}const v=b.filter(C=>C.includes("CodeYam Log Level 1"));if(v.length>0){const C=v[v.length-1];s(C.replace(/.*CodeYam Log Level 1: /,""))}const N=b.find(C=>C.includes("$$INTERACTIVE_SERVER_URL$$:"));if(N){const C=N.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(C),h(!0)}const w=b.find(C=>C.includes("$$INTERACTIVE_SCENARIO_URLS$$:"));if(w)try{const C=w.split("$$INTERACTIVE_SCENARIO_URLS$$:")[1].trim();u(JSON.parse(C))}catch{}b.some(C=>C.includes("CodeYam: Exiting start.js"))&&a(!0)}}catch{}};f().catch(()=>{});const y=setInterval(()=>{f().catch(()=>{})},500);return()=>clearInterval(y)},[e,t,p]);const m=ce(()=>{s(""),a(!1),l(null),u(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,scenarioUrlMap:c,isCompleted:o,resetLogs:m}}function hn({projectSlug:e,onClose:t}){const[r,s]=P("Loading logs..."),[o,a]=P(!0),[i,l]=P(!0),[c,u]=P("all"),p=ye(null);return se(()=>{const h=async()=>{try{const m=await fetch(`/api/logs/${e}`);if(m.ok){const f=await m.text();if(c==="all")s(f);else{const y=f.trim().split(`
|
|
19
|
+
`).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=c});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
+
`))}i&&p.current&&setTimeout(()=>{var y;(y=p.current)==null||y.scrollTo({top:p.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${m.status} - ${await m.text()}`)}catch(m){s(`Error fetching logs: ${m.message}`)}};if(h().catch(()=>{}),o){const m=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(m)}},[e,o,i,c]),se(()=>{const h=m=>{m.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:d("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:h=>u(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:o,onChange:h=>a(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:p,children:r})]})})}function St({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"}},s=r[e]||r.other,o=t==="large"?18:14,a=t==="large"?32:18,i=()=>{switch(e){case"library":return n(_d,{size:o,color:s.iconColor});case"visual":return n(Br,{size:o,color:s.iconColor});case"type":return n(Zh,{size:o,color:s.iconColor});case"data":return n(Qh,{size:o,color:s.iconColor});case"index":return n(qh,{size:o,color:s.iconColor});case"functionCall":return n(Fl,{size:o,color:s.iconColor});case"class":return n(Gh,{size:o,color:s.iconColor});case"method":return n(Fl,{size:o,color:s.iconColor});case"other":return n($l,{size:o,color:s.iconColor});default:return n($l,{size:o,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${a}px`,height:`${a}px`},children:i()})}function Id({filePath:e,maxLength:t=60,className:r,style:s}){const a=((l,c)=>{if(l.length<=c)return l;const u="...",p=c-u.length,h=Math.ceil(p*.4),m=Math.floor(p*.6),f=l.slice(0,h),y=l.slice(-m),g=f.lastIndexOf("/"),x=y.indexOf("/"),b=g>h*.5?f.slice(0,g+1):f,v=x!==-1&&x<m*.5?y.slice(x):y;return`${b}${u}${v}`})(e,t),i=a!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:a})}function Xo({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:o=!1,scenarioCount:a=0,additionalContent:i}){return d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"flex items-center gap-1",children:[n(St,{type:e.entityType||"other"}),d(ke,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&a>0&&` (${a})`]}),n(Id,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const ea={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function of({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:o=0,queueJobs:a=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var J,j,D;const[c,u]=P(!1),[p,h]=P(!1),[m,f]=P(null),[y,g]=P(new Set),[x,b]=P(new Set),[v,N]=P(!1),w=!!i||a.length>0,C=!!i,S=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),T=(e==null?void 0:e.readyToBeCaptured)??0,_=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(T===0||_>=T);const $=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,M=w,{lastLine:R}=Qt(t,M),z=C||a.length>0,O=new Set(((J=i==null?void 0:i.entities)==null?void 0:J.map(A=>A.sha))||[]),U=l.filter(A=>!(A.currentEntityShas||[]).some(E=>O.has(E))),W=(()=>{const L=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&$){const E=e.analysisCompletedAt||e.createdAt;if(new Date(E).getTime()>L)return!0}if(U.length>0){const E=U[0],F=E.analysisCompletedAt||E.archivedAt||E.createdAt;if(F&&new Date(F).getTime()>L)return!0}return!1})();return se(()=>{const A=(i==null?void 0:i.id)||null;w&&!p&&A!==m&&h(!0),!w&&m!==null&&f(null)},[w,i==null?void 0:i.id,p,m]),d(ve,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${p?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!p&&d("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[z?n(It,{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(Qo,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:z?"Analyzing...":"Activity: No Activity Yet"}),z&&n("button",{onClick:A=>{A.stopPropagation(),u(!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"})]}),p&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[z?n(It,{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(Qo,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:z?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>u(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(At,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),d("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[z&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Qo,{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?d("div",{className:"space-y-1.5",children:[(v?S:S.slice(0,3)).map(A=>n(Xo,{entity:A,nameSize:"11px",pathSize:"10px",pathMaxLength:150},A.sha)),S.length>3&&n("button",{onClick:()=>N(A=>!A),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ea,"aria-label":v?"Show fewer entities":`Show ${S.length-3} more entities`,children:v?"Show less":`+${S.length-3} more`}),R&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:R})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((A,L)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:A},L)),i.entityNames.length>5&&d("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):d("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((j=i.entityShas)==null?void 0:j.length)||0," ",((D=i.entityShas)==null?void 0:D.length)===1?"entity":"entities","..."]}),R&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:R})]})})]}),a.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Xh,{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:a.map(A=>{var F,I;const L=y.has(A.id),E=L?A.entities:A.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:A.entities.length>0?d("div",{className:"space-y-1.5",children:[E.map(K=>n(Xo,{entity:K,nameSize:"10px",pathSize:"9px",pathMaxLength:120},K.sha)),A.entities.length>3&&n("button",{onClick:()=>{g(K=>{const Q=new Set(K);return Q.has(A.id)?Q.delete(A.id):Q.add(A.id),Q})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ea,"aria-label":L?"Show fewer entities":`Show ${A.entities.length-3} more entities`,children:L?"Show less":`+${A.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[A.type==="analysis"&&n(ve,{children:A.entityNames&&A.entityNames.length>0?d("div",{className:"space-y-0.5",children:[A.entityNames.slice(0,5).map((K,Q)=>n("div",{children:K},Q)),A.entityNames.length>5&&d("div",{className:"italic",children:["+",A.entityNames.length-5," more"]})]}):`Analyzing ${((F=A.entityShas)==null?void 0:F.length)||0} ${((I=A.entityShas)==null?void 0:I.length)===1?"entity":"entities"}`}),A.type==="recapture"&&"Recapturing scenario",A.type==="debug-setup"&&"Setting up debug environment"]})},A.id)})})]}),W&&U.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(qa,{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:U.slice(0,3).map((A,L)=>{const E=A.entities||[],F=A.analysisCompletedAt||A.archivedAt||A.createdAt||"",I=(()=>{if(!F)return"";const Y=Date.now()-new Date(F).getTime(),B=Math.floor(Y/6e4),H=Math.floor(Y/36e5);return H>0?`${H}h ago`:B>0?`${B}m ago`:"just now"})(),K=x.has(L),V=(K?E:E.slice(0,3)).map(Y=>{var B,H,ne;return{...Y,scenarioCount:((ne=(H=(B=Y.analyses)==null?void 0:B[0])==null?void 0:H.scenarios)==null?void 0:ne.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:E.length>0&&d("div",{className:"space-y-1.5",children:[V.map((Y,B)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Xo,{entity:Y,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:Y.scenarioCount})}),B===0&&I&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:I})]},Y.sha)),E.length>3&&n("button",{onClick:()=>{b(Y=>{const B=new Set(Y);return B.has(L)?B.delete(L):B.add(L),B})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ea,"aria-label":K?"Show fewer entities":`Show ${E.length-3} more entities`,children:K?"Show less":`+${E.length-3} more`})]})},L)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(ke,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),c&&t&&n(hn,{projectSlug:t,onClose:()=>u(!1)})]})}function Et(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function qr(e){const{file_id:t,project_id:r,commit_id:s,file_path:o,entity_type:a,entity_branches:i,analyses:l,commit:c,created_at:u,updated_at:p,...h}=e,m=(i??[]).map(g=>g.branch_id),f=l?l.map(Zt):void 0,y=c?Fn(c):void 0;return Et({...h,fileId:t,projectId:r,commitId:s,filePath:o,entityType:a,commit:y,analyses:f,branchIds:m,createdAt:u,updatedAt:p})}function ii(e){return Et({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 po(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:o,created_at:a,updated_at:i,github_token:l,configuration:c,team_id:u,...p}=e;return Et({...p,branches:t?t.map(Rn):void 0,files:r?r.map(ii):void 0,analyzedAt:s,contentChangedAt:o,createdAt:a,updatedAt:i})}function af(e){const{id:t,project_id:r,user_id:s,scenario_id:o,thumbs_up:a,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Et({id:t,projectId:r,userId:s,scenarioId:o,thumbsUp:!!a,user:l})}function lf(e){const{id:t,project_id:r,user_id:s,scenario_id:o,text:a,created_at:i,updated_at:l,user:c}=e,u=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return Et({id:t,projectId:r,userId:s,scenarioId:o,text:a,createdAt:i,updatedAt:l,user:u})}function Od(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:o,user_scenarios:a,scenario_comments:i,approved:l,...c}=e,u=o?Zt(o):void 0,p=a?a.map(af):void 0,h=i?i.map(lf):void 0;return Et({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:u,userScenarios:p,comments:h})}function cf(e){return Et({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Zt(e.analysis):void 0,entity:e.entity?qr(e.entity):void 0,branch:e.branch?Rn(e.branch):void 0,createdAt:e.created_at})}function Zt(e){const{project_id:t,commit_id:r,file_id:s,file_path:o,entity_sha:a,entity_type:i,entity_name:l,previous_analysis_id:c,file:u,entity:p,commit:h,project:m,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:v,completed_at:N,created_at:w,updated_at:C,indirect:S,...k}=e,T=p?qr(p):void 0,_=u?ii(u):void 0,$=m?po(m):void 0,M=h?Fn(h):void 0,R=f?f.map(Od):void 0,z=y?y.map(cf):void 0,O=z?z.map(U=>U.branch):void 0;return Et({...k,projectId:t,commitId:r,fileId:s,filePath:o,entitySha:a,entityType:i,entityName:l,previousAnalysisId:c,entity:T,file:_,commit:M,project:$,scenarios:R,analysisBranches:z,branches:O,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:b,committedAt:v,completedAt:N,createdAt:w,updatedAt:C,indirect:!!S})}function li(e){return Et({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Fn(e.commit):void 0,branch:e.branch?Rn(e.branch):void 0})}function df(e){const{project_id:t,commit_id:r,created_at:s,updated_at:o,success:a,...i}=e;return Et({...i,projectId:t,commitId:r,createdAt:s,updatedAt:o,success:!!a})}function Fn(e){const{project_id:t,branch_id:r,branch:s,background_jobs:o,merged_branch_id:a,mergedBranch:i,ai_message:l,html_url:c,author:u,analyses:p,entities:h,commit_branches:m,committed_at:f,analyzed_at:y,...g}=e,x=s?Rn(s):void 0,b=i?Rn(i):void 0,v=(o==null?void 0:o.length)>0?df(o[o.length-1]):void 0,N=(p??[]).map(Zt),w=(h??[]).map(qr),C=(m==null?void 0:m.length)>0?m.map(li):void 0;return u&&(u.username=u.preferredUsername??u.username),Et({...g,projectId:t,branchId:r,branch:x,backgroundJob:v,mergedBranchId:a,mergedBranch:b,aiMessage:l,htmlUrl:c,author:u,analyses:N,entities:w,commitBranches:C,committedAt:f,analyzedAt:y})}function Rn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:o,active_at:a,created_at:i,updated_at:l,primary:c,...u}=e,p=s?s.map(Fn):void 0,h=o?o.flatMap(m=>Zt(m.analysis)):void 0;return Et({...u,projectId:t,contentChangedAt:r,commits:p,analyses:h,activeAt:a,createdAt:i,updatedAt:l,primary:!!c})}var so;class uf{constructor(){Al(this,so,new pf)}transformQuery(t){return Pl(this,so).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}so=new WeakMap;class pf extends bm{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 Ne=()=>null;function Be(e=!1){return t=>(t=t.defaultTo(wt`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const hf={analyzed_at:Ne(),configuration:Ne(),content_changed_at:Ne(),created_at:Ne(),description:Ne(),github_token:Ne(),id:Ne(),metadata:Ne(),name:Ne(),path:Ne(),slug:Ne(),team_id:Ne(),updated_at:Ne()},mf=Object.keys(hf);async function ff(e){await e.schema.createTable("projects").addColumn("id","uuid",t=>t.primaryKey()).addColumn("name","text").addColumn("slug","text",t=>t.notNull()).addColumn("github_token","text").addColumn("description","text").addColumn("path","text").addColumn("configuration","text").addColumn("metadata","text").addColumn("content_changed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("team_id","integer").ifNotExists().execute()}async function gf(e){await e.schema.createTable("analyses").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("entity_sha","varchar").addColumn("entity_name","varchar").addColumn("status","text").addColumn("metadata","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).addColumn("tree_sha","text").addColumn("analyzed_tree_sha","text").addColumn("dependency_analyzed_tree_sha","text").addColumn("previous_analysis_id","uuid").addColumn("branch_commit_sha","varchar").addColumn("indirect","boolean").addColumn("committed_at","datetime").addColumn("completed_at","datetime").addColumn("file_path","varchar").addColumn("entity_type","varchar").ifNotExists().execute()}const yf={active:Ne(),analysis_id:Ne(),branch_id:Ne(),created_at:Ne(),entity_sha:Ne(),id:Ne()},xf=Object.keys(yf);async function bf(e){await e.schema.createTable("analysis_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("analysis_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addColumn("created_at","datetime",Be()).ifNotExists().execute()}async function vf(e){await e.schema.createTable("background_jobs").addColumn("commit_id","uuid",t=>t.notNull()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("progress","text").addColumn("success","boolean").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const wf={active_at:Ne(),content_changed_at:Ne(),created_at:Ne(),id:Ne(),metadata:Ne(),name:Ne(),primary:Ne(),project_id:Ne(),ref:Ne(),sha:Ne(),updated_at:Ne()},Ld=Object.keys(wf);async function Nf(e){await e.schema.createTable("branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("ref","text").addColumn("name","text").addColumn("sha","text").addColumn("primary","boolean",t=>t.notNull().defaultTo(!1)).addColumn("metadata","text").addColumn("content_changed_at","datetime",Be()).addColumn("active_at","datetime").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function Sf(e){await e.schema.createTable("commit_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("branch_id","uuid").addColumn("commit_id","uuid").addColumn("active","boolean").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}const Cf={ai_message:Ne(),analyzed_at:Ne(),author_github_username:Ne(),branch_id:Ne(),committed_at:Ne(),created_at:Ne(),files:Ne(),html_url:Ne(),id:Ne(),merged_branch_id:Ne(),message:Ne(),metadata:Ne(),project_id:Ne(),sha:Ne(),title:Ne(),url:Ne()},zd=Object.keys(Cf),kf=zd.filter(e=>e!=="files");async function Ef(e){await e.schema.createTable("commits").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid").addColumn("merged_branch_id","uuid").addColumn("message","text").addColumn("ai_message","text").addColumn("title","varchar").addColumn("author_github_username","varchar").addColumn("url","varchar").addColumn("html_url","varchar").addColumn("sha","varchar",t=>t.notNull()).addColumn("files","text").addColumn("metadata","text").addColumn("committed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function _f(e){await e.schema.createTable("debug_reports").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull()).addColumn("s3_key","varchar",t=>t.notNull()).addColumn("file_size_bytes","bigint").addColumn("metadata","text").addColumn("status","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function jf(e){await e.schema.createTable("labs_requests").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull().unique()).addColumn("name","varchar",t=>t.notNull()).addColumn("email","varchar",t=>t.notNull()).addColumn("org_name","varchar").addColumn("org_size","varchar").addColumn("project_size","varchar").addColumn("tech_stack","varchar").addColumn("status","varchar").addColumn("unlock_code","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const Pf={commit_id:Ne(),created_at:Ne(),description:Ne(),documentation:Ne(),entity_type:Ne(),file_id:Ne(),file_path:Ne(),metadata:Ne(),name:Ne(),project_id:Ne(),quality:Ne(),sha:Ne(),updated_at:Ne()},Bd=Object.keys(Pf);async function Af(e){await e.schema.createTable("entities").addColumn("project_id","uuid",t=>t.notNull()).addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("name","varchar").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("entity_type","varchar").addColumn("file_path","varchar").addColumn("description","text").addColumn("documentation","text").addColumn("metadata","text").addColumn("quality","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const Tf={active:Ne(),branch_id:Ne(),entity_sha:Ne()},Mf=Object.keys(Tf);async function $f(e){await e.schema.createTable("entity_branches").addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addPrimaryKeyConstraint("entity_branches_pkey",["branch_id","entity_sha"]).ifNotExists().execute()}async function Ff(e){await e.schema.createTable("entity_statements").addColumn("id","integer",t=>t.autoIncrement().primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("statement_sha","varchar",t=>t.notNull()).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}const Rf={created_at:Ne(),deleted:Ne(),id:Ne(),metadata:Ne(),name:Ne(),path:Ne(),project_id:Ne(),updated_at:Ne()},Df=Object.keys(Rf);async function If(e){await e.schema.createTable("files").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar").addColumn("path","varchar",t=>t.notNull()).addColumn("deleted","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("metadata","text").ifNotExists().execute()}async function Of(e){await e.schema.createTable("github_payloads").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("payload_type","varchar").addColumn("payload","text").addColumn("after","varchar").addColumn("commit_sha","varchar").addColumn("ref","varchar").addColumn("committed_at","datetime").addColumn("error","text").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Lf(e){await e.schema.createTable("github_users").addColumn("username","varchar",t=>t.primaryKey()).addColumn("preferred_username","varchar").addColumn("avatar_url","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function zf(e){await e.schema.createTable("scenario_comments").addColumn("id","serial",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("scenario_id","uuid").addColumn("user_id","uuid").addColumn("text","text").addColumn("metadata","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute()}async function Bf(e){await e.schema.createTable("editor_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar",t=>t.notNull()).addColumn("description","text").addColumn("component_name","varchar").addColumn("component_path","varchar").addColumn("url","varchar").addColumn("type","varchar").addColumn("screenshot_path","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute();for(const t of["component_name","component_path","url","type","screenshot_path"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}for(const t of["viewport_width","viewport_height"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"integer").execute()}catch{}for(const t of["dimensions","screenshot_paths"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"text").execute()}catch{}for(const t of["page_file_path","entity_sha","display_name"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","dimension","dimensions"]).execute();for(const r of t){const s=r;s.dimension&&!s.dimensions&&await e.updateTable("editor_scenarios").set({dimensions:JSON.stringify([s.dimension])}).where("id","=",s.id).execute()}}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","screenshot_path","screenshot_paths","dimensions"]).execute();for(const r of t){const s=r;if(s.screenshot_path&&!s.screenshot_paths){let o="Default";try{const a=s.dimensions?JSON.parse(s.dimensions):null;Array.isArray(a)&&a.length>0&&(o=a[0])}catch{}await e.updateTable("editor_scenarios").set({screenshot_paths:JSON.stringify({[o]:s.screenshot_path})}).where("id","=",s.id).execute()}}}catch{}}const Yf={analysis_id:Ne(),approved:Ne(),created_at:Ne(),description:Ne(),id:Ne(),metadata:Ne(),name:Ne(),previous_version_id:Ne(),project_id:Ne()},Gs=Object.keys(Yf);async function Uf(e){await e.schema.createTable("scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("analysis_id","uuid").addColumn("name","varchar").addColumn("description","text").addColumn("metadata","text").addColumn("approved","boolean").addColumn("previous_version_id","uuid").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Wf(e){await e.schema.createTable("statements").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("text","text",t=>t.notNull()).addColumn("llm_call_id","varchar").addColumn("results","text").addColumn("issues","text").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Jf(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Hf(e){await e.schema.createTable("user_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("scenario_id","uuid",t=>t.notNull()).addColumn("user_id","uuid",t=>t.notNull()).addColumn("thumbs_up","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Vf(e){await e.schema.createTable("user_teams").addColumn("team_id","integer",t=>t.notNull()).addColumn("user_auth_id","uuid",t=>t.notNull()).addPrimaryKeyConstraint("user_teams_pkey",["team_id","user_auth_id"]).ifNotExists().execute()}async function Kf(e){await e.schema.createTable("users").addColumn("auth_id","uuid",t=>t.primaryKey()).addColumn("email","varchar").addColumn("github_username","varchar").addColumn("github_token","varchar").addColumn("verified","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}const Gf=!!Dn("ENABLE_QUERY_LOGGING"),qf=!!Dn("ENABLE_QUERY_ERROR_LOGGING");Dn("USE_LOCAL_POSTGRESQL_FOR_TESTING");let xs;function $e(){if(!xs){const e=Ud();if(e==="sqlite")xs=Qf();else if(e==="postgresql")xs=Zf();else throw new Error(`Unknown database type: ${e}`)}return xs}function Qf(e){if(e||(e=Dn("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=G.dirname(e);if(!q.existsSync(r))q.mkdirSync(r,{recursive:!0,mode:493});else try{q.chmodSync(r,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const s=new gm(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const o=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&o.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(o){console.error("CodeYam DB ERROR: Failed to verify database schema:",o)}return new Md({dialect:new wm({database:s}),plugins:[new vm,new uf],log:Yd})}function Zf(){const e=eg();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new ym({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Md({dialect:new Nm({pool:t}),log:Yd})}let ta=null;function Ln(){return ta||(ta=Xf(Ud())),ta}function Yd(e){e.level==="error"?qf&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Gf&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Xf(e){if(e==="sqlite")return Sm;if(e==="postgresql")return Cm;throw new Error(`Unknown database type: ${e}`)}function Ud(){if(Dn("SQLITE_PATH"))return"sqlite";if(Dn("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function C_(e){await ff(e),await gf(e),await bf(e),await vf(e),await Nf(e),await Sf(e),await Ef(e),await _f(e),await Bf(e),await Af(e),await $f(e),await Ff(e),await If(e),await Of(e),await Lf(e),await jf(e),await zf(e),await Uf(e),await Wf(e),await Jf(e),await Hf(e),await Vf(e),await Kf(e)}function eg(){const e=Dn("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Dn(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const tg=()=>crypto.randomUUID();function ng(e){const{id:t,projectId:r,activeAt:s,contentChangedAt:o,metadata:a,...i}=e;return delete i.commits,delete i.files,delete i.analyses,delete i.createdAt,delete i.updatedAt,{...i,id:t??tg(),project_id:r,active_at:s,content_changed_at:o,metadata:a?JSON.stringify(a):null}}var st=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(st||{});const ho="Default Scenario";let rg="<main>";function sg(){return rg}function Ol(e,...t){Ie(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Ie(...e){const t=sg(),r=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
21
|
+
${o.stack}`:typeof o=="object"?og(o):String(o)}).filter(Boolean).join(`
|
|
22
|
+
`),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
|
|
23
|
+
`);return}console.log(s.replace(/\n/g,"\r"))}function og(e,t=2){function r(s,o=new WeakMap){return s===null||typeof s!="object"?s:o.has(s)?`"[Circular: ${s.constructor.name}]"`:(o.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const c=r(l,o);return typeof l=="string"?`"${c}"`:c}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let c;return typeof l>"u"?null:(typeof l=="function"?c=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?c=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?c=r(l,o):typeof l=="string"?c=`"${l.replace(/"/g,'\\"')}"`:c=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${c}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const o=r(e);if(!t)return o;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(a){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:a,pureStringifyError:s,serialized:o}),o}}}function qs(e,t){try{let r=function(a){var i,l;if(et.isFunctionDeclaration(a)&&Ar(a)){const c=((i=a.name)==null?void 0:i.text)||"default",u=a.getText(s),p=na(a);o.push({name:c,code:u,sha:kn(t,c,u),entityType:"function",isDefault:p})}else if(et.isClassDeclaration(a)&&Ar(a)){const c=((l=a.name)==null?void 0:l.text)||"default",u=a.getText(s),p=na(a),h=u.includes("React.")||u.includes("jsx")||u.includes("tsx");o.push({name:c,code:u,sha:kn(t,c,u),entityType:h?"component":"class",isDefault:p})}else if(et.isInterfaceDeclaration(a)&&Ar(a)){const c=a.name.text,u=a.getText(s);o.push({name:c,code:u,sha:kn(t,c,u),entityType:"interface",isDefault:!1})}else if(et.isTypeAliasDeclaration(a)&&Ar(a)){const c=a.name.text,u=a.getText(s);o.push({name:c,code:u,sha:kn(t,c,u),entityType:"type",isDefault:!1})}else if(et.isVariableStatement(a)&&Ar(a)){const c=na(a);a.declarationList.declarations.forEach(u=>{var p;if(et.isIdentifier(u.name)){const h=u.name.text,m=a.getText(s),f=((p=u.initializer)==null?void 0:p.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));o.push({name:h,code:m,sha:kn(t,h,m),entityType:y?"component":"variable",isDefault:c})}})}else if(et.isExportAssignment(a)){const c=a.getText(s);o.push({name:"default",code:c,sha:kn(t,"default",c),entityType:"unknown",isDefault:!0})}else if(et.isExportDeclaration(a)&&a.exportClause&&et.isNamedExports(a.exportClause)){const c=a.getText(s);for(const u of a.exportClause.elements){const p=u.name.text;o.push({name:p,code:c,sha:kn(t,p,c),entityType:"unknown",isDefault:!1})}}et.forEachChild(a,r)};const s=et.createSourceFile(t,e,et.ScriptTarget.Latest,!0),o=[];return r(s),o}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Ar(e){if(!et.canHaveModifiers(e))return!1;const t=et.getModifiers(e);return t?t.some(r=>r.kind===et.SyntaxKind.ExportKeyword):!1}function na(e){if(!et.canHaveModifiers(e))return!1;const t=et.getModifiers(e);return t?t.some(r=>r.kind===et.SyntaxKind.DefaultKeyword):!1}function kn(e,t,r){const s=dr.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function ag(e){var u;const{webapp:t,port:r,environmentVariables:s,packageManager:o}=e,a=t==null?void 0:t.startCommand;if(!a)return`${o} ${o==="npm"?"run ":""}dev`;const i=((u=a.args)==null?void 0:u.map(p=>p.replace(/\$PORT/g,String(r))))??[],l=[];for(const p of s)if(p.key&&p.value!==void 0){const h=String(p.value).replace(/'/g,"'\\''");l.push(`${p.key}='${h}'`)}if(a.env)for(const[p,h]of Object.entries(a.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${p}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return a.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${a.command} ${i.join(" ")}`}function ig(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=G.normalize(e),s=[...t].sort((o,a)=>{var i,l;return(((i=a.path)==null?void 0:i.length)??0)-(((l=o.path)==null?void 0:l.length)??0)});for(const o of s){const a=G.normalize(o.path??".");if(a==="."||r.startsWith(a+G.sep)||r===a)return o}return t[0]}function lg(e){const{filePath:t,webapps:r,environmentVariables:s,port:o,packageManager:a}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=ig(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=ag({webapp:i,port:o,environmentVariables:s,packageManager:a});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??a,startCommand:l,url:`http://localhost:${o}/static/codeyam-sample`}}function ur(e,t,r=[]){const s=Array.isArray(t)?t:[t];return o=>o.columns(s).doUpdateSet(a=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,a.ref(`excluded.${l}`)]))})}async function cg(e){if(e.length===0)return[];const t=$e(),r=e.map(ng);try{return(await t.insertInto("branches").values(r).onConflict(ur(r[0],"id",["created_at"])).returningAll().execute()).map(Rn)}catch(s){return Ie("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(o=>o.id)}),[]}}function dg(e){const{jsonObjectFrom:t}=Ln();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 ug({ids:e,analysisId:t}){const r=$e();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Ie("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Ie("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function pg(...e){try{const t=dr.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 ra(e,t){return t.map(r=>hg(e,r))}function hg(e,t){return wt` ${wt.ref(e)}.${wt.ref(t)}`.as(t)}function mg(e,t,r){return t.map(s=>fg(e,s,r))}function fg(e,t,r){return wt` ${wt.ref(e)}.${wt.ref(t)}`.as(`_cy_${r}:${t}`)}function gg(e,...t){const r={};for(const[s,o]of Object.entries(e)){const a=s.match(/^_cy_(.+?):(.+)$/);if(a){const[,i,l]=a;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=o}return r}const yg=50;function xg(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function Ll({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:o,commitIds:a,branchCommitSha:i,limit:l,excludeMetadata:c}){const u=$e(),{jsonObjectFrom:p,jsonArrayFrom:h}=Ln();let m=c?u.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"]):u.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(a){if(a.length===0)return null;m=m.where("commit_id","in",a)}return s&&(m=m.where("entity_name","=",s)),o&&(m=m.where("entity_sha","in",o)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),c?u.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(ra("scenarios",Gs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):u.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("entities").select(ra("entities",Bd)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(ra("scenarios",Gs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function gn(e){const{ids:t,fileIds:r,entityShas:s,commitIds:o}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:o,key:"commitIds"}}).find(([c,{arr:u}])=>(u==null?void 0:u.length)>0);let l=[];if(i){const[c,{arr:u,key:p}]=i,h=xg(u,yg),m=[];for(let f=0;f<h.length;f++){const y=h[f],x=await Ll({...e,[p]:y}).execute();x&&m.push(...x)}l=m}else{const u=await Ll(e).execute();if(!u||u.length===0)return Ie("CodeYam: No analyses found",null,e),null;l=u}return l.length===0?null:l.map(Zt)}catch(a){return Ie("CodeYam Error: Database error in loadAnalyses",a,e),null}}function bg(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=Ln();let o=e.selectFrom("analysis_branches").select(xf).select(a=>s(a.selectFrom("branches").select(Ld).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(o=t(o)),r(o)}async function Xt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}){const f=$e(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):s&&(g=g.where("file_id","=",s)),a&&(g=g.where("entity_name","=",a)),o?g=g.where("commit_id","=",o):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:b}=Ln();g=g.select(w=>{const C=[];return C.push(x(w.selectFrom("entities").select(Bd).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&C.push(x(w.selectFrom("files").select(Df).whereRef("files.id","=","analyses.file_id")).as("file")),u&&C.push(x(w.selectFrom("projects").select(mf).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&C.push(b(w.selectFrom("scenarios").select(Gs).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),m&&C.push(bg(w,S=>S.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),p&&C.push(x(w.selectFrom("commits").select(zd).select(S=>dg(S).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const v=await g.executeTakeFirst(),N=Date.now()-y;if(!v)return Ie(!!i?`CodeYam: Analysis cache miss for dependency tree SHA ${i.substring(0,12)}...`:`CodeYam Error: Analysis not found${a?` for ${a}`:""}${e?` (id=${e})`:""}`,null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}),null;if(N>100&&p){const w=v.commit,C=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(C/1024)}KB)`,{id:v.id,entityName:v.entity_name})}return Zt(v)}catch(g){return Ie("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}),null}}async function ci({projectId:e,ids:t,names:r,includeInactive:s}){const o=$e();try{let a=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];a=a.where("id","in",t)}if(r){if(r.length===0)return[];a=a.where("name","in",r)}return s||(a=a.where("active_at","is not",null)),(await a.execute()).map(Rn)}catch(a){return Ie("CodeYam Error: Database error loading branches",a,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function vg({projectId:e,commitId:t,branchId:r,active:s,includeBranches:o}){const a=$e();try{let i=a.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,u=>u.select(mg("branches",Ld,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(u=>gg(u,"branch")).map(li)}catch(i){return Ie("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:o}),null}}async function wg(e){if(e.length===0)return new Map;const t=$e();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(a=>{a.branch_id&&s.add(a.branch_id),a.merged_branch_id&&s.add(a.merged_branch_id)}),s.size===0)return new Map;const o=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(o.map(a=>[a.id,a]))}catch(r){return Ie("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Ng(e){if(e.length===0)return new Map;const t=$e(),{jsonObjectFrom:r,jsonArrayFrom:s}=Ln();try{const o=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(Gs).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),a=new Map;return o.forEach(i=>{const l=a.get(i.commit_id)||[];l.push(i),a.set(i.commit_id,l)}),a}catch(o){return Ie("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function Sg(e){if(e.length===0)return new Map;const t=$e();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(o=>{const a=s.get(o.commit_id)||[];a.push(o),s.set(o.commit_id,a)}),s}catch(r){return Ie("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Qs({projectId:e,branchId:t,ids:r,shas:s,fileNames:o,limit:a=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=$e(),{jsonObjectFrom:c}=Ln(),u=Date.now();try{let p;if(i){const v=kf.map(N=>`commits.${N}`);p=l.selectFrom("commits").select(v)}else p=l.selectFrom("commits").selectAll("commits").select(v=>[c(v.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",v.ref("commits.author_github_username"))).as("author")]);if(e&&(p=p.where("project_id","=",e)),r){if(r.length===0)return[];p=p.where("id","in",r)}if(s){if(s.length===0)return[];p=p.where("sha","in",s)}if(o&&o.length>0){const v=wt.join(o.map(N=>wt`${N}`),wt`, `);p=p.where(wt`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${wt.ref("commits.files")}) AS f
|
|
27
|
+
WHERE json_extract(f.value, '$.fileName') IN (${v})
|
|
28
|
+
)
|
|
29
|
+
`)}t&&(p=p.where("branch_id","=",t));const h=await p.orderBy("committed_at","desc").limit(a).execute(),m=Date.now()-u;if(!h||h.length===0)return[];if(m>100){const v=h.reduce((N,w)=>N+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${m}ms (${h.length} commits, totalFiles: ${Math.round(v/1024)}KB)`)}if(i)return h.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Fn);const f=h.map(v=>v.id),[y,g,x]=await Promise.all([wg(f),Ng(f),Sg(f)]);return h.map(v=>{const N=v.branch_id?y.get(v.branch_id):void 0,w=v.merged_branch_id?y.get(v.merged_branch_id):void 0,C=g.get(v.id)||[],S=x.get(v.id)||[];return{...v,branch:N,mergedBranch:w,analyses:C,entities:S}}).map(Fn)}catch(p){return Ie("CodeYam Error: Database error loading commits",p,{projectId:e,branchId:t,ids:r,shas:s,limit:a}),[]}}async function tt({projectId:e,branchId:t,fileIds:r,filePaths:s,names:o,shas:a,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||o&&o.length==0||a&&a.length==0)return[];if(a&&a.length>50){const c=[];for(let u=0;u<a.length;u+=50){const p=a.slice(u,u+50),h=await tt({projectId:e,branchId:t,fileIds:r,filePaths:s,names:o,shas:p,excludeMetadata:i});h&&c.push(...h)}return c}const l=$e();try{const p=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,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!a,h=>h.where("entities.sha","in",a)).$if(!!s,h=>h.where("entities.file_path","in",s)).$if(!!o,h=>h.where("entities.name","in",o)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!p||p.length===0?null:p.map(qr)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:a}),null}}function Cg(e,t){const{jsonArrayFrom:r}=Ln();let s=e.selectFrom("entity_branches").select(Mf);return t&&(s=t(s)),r(s)}async function Wd({projectId:e,sha:t,silent:r}){const s=$e();try{const o=await s.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>Cg(a,i=>i.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return o?qr(o):(!r&&process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Ie(`CodeYam Error: Load Entity: Entity not found (sha=${t==null?void 0:t.substring(0,12)})`,null,{projectId:e,sha:t}),null)}catch(o){return Ie("CodeYam Error: Load Entity: Database error",o,{projectId:e,sha:t}),null}}const sa=1e3;async function Jd({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const u=t.slice(c,c+50),p=await Jd({projectId:e,filePaths:u,fileIds:r,fileNames:s});p&&l.push(...p)}return l}const o=$e(),a=[];let i=0;try{for(;;){let l=o.selectFrom("files").selectAll().where("project_id","=",e).limit(sa).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(s){if(s.length===0)return[];l=l.where("name","in",s)}const c=await l.execute();if(!c||c.length===0||(a.push(...c),c.length<sa))break;i+=sa}return a==null?void 0:a.map(ii)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function di({id:e,slug:t,withBranches:r,withFiles:s,silent:o}){try{let i=$e().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 null;const c=po(l);return s&&(c.files=await Jd({projectId:c.id})),r&&(c.branches=await ci({projectId:c.id,includeInactive:!1})),c}catch{return null}}function Zs(e,t){const r={...e};for(const s in t){const o=t[s],a=e[s];o!=null&&typeof o=="object"&&!Array.isArray(o)&&a!==void 0&&a!==null&&typeof a=="object"&&!Array.isArray(a)?r[s]=Zs(a,o):o!==void 0&&(r[s]=o)}return r}async function pn({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:o,updateCallback:a}){for(let c=0;c<=4;c++)try{return await $e().transaction().execute(async u=>{const p=await u.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!p)return Ie(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const h=p.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=Zs(r??{},{currentRun:s});else if(!r&&!a)return h;const m=r?Zs(h,r):h;if(o&&m.currentRun){const f={...m.currentRun,archivedAt:new Date().toISOString()};m.historicalRuns=[...m.historicalRuns||[],f]}a&&await a(m);try{return await u.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",p.id).returning(["id"]).executeTakeFirst()?m:(Ie(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),h)}catch(f){return Ie(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),h}})}catch(u){const p=u instanceof Error&&u.message.includes("database is locked");if(p&&c<4){const h=250*Math.pow(2,c);await new Promise(m=>setTimeout(m,h));continue}return Ie(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${p?` after ${c+1} attempts`:""}`,u),null}return null}async function Hd(e,t,r="analysis"){try{return await $e().transaction().execute(async s=>{const o=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return Ie(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const a=Zt(o);return t(a.metadata,a),await s.updateTable("analyses").set({metadata:JSON.stringify(a.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?a.metadata:(Ie(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Ie(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function pr(e,t,r="capture"){for(let a=0;a<=4;a++)try{return await $e().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Ie(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=Zt(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(Ie(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&a<4){const c=250*Math.pow(2,a);await new Promise(u=>setTimeout(u,c));continue}return Ie(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${a+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function or({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await $e().transaction().execute(async o=>{const a=await o.selectFrom("projects").selectAll().$if(!!e,c=>c.where("id","=",e)).$if(!!t,c=>c.where("slug","=",t)).executeTakeFirst();if(!a)return Ie(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=a.metadata||{};if(!r&&!s)return i;const l=r?Zs(i,r):i;s&&await s(l,po(a));try{return await o.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",a.id).returningAll().executeTakeFirst()?l:(Ie(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return Ie(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(o){return Ie(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}const kg=()=>crypto.randomUUID();function Eg(e){const{id:t,projectId:r,analysisId:s,previousVersionId:o,analysis:a,metadata:i,data:l,...c}=e;return delete c.userScenarios,delete c.comments,"created_at"in c&&delete c.created_at,{...c,id:t??kg(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:o}}async function _g(e){if(e.length===0)return[];const t=$e(),r=e.map(Eg);try{return(await t.insertInto("scenarios").values(r).onConflict(ur(r[0],"id",["created_at"])).returningAll().execute()).map(Od)}catch(s){return Ie("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const jg=()=>crypto.randomUUID();function Pg(e){const{id:t,commitId:r,branchId:s,...o}=e;return delete o.commit,delete o.branch,{...o,id:t??jg(),commit_id:r,branch_id:s}}async function zl(e){if(e.length===0)return[];const t=$e(),r=e.map(Pg);try{return(await t.insertInto("commit_branches").values(r).onConflict(ur(r[0],"id",["created_at"])).returningAll().execute()).map(li)}catch(s){return Ie("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function Ag(e,t){const r=$e(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(ur(s,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return Ie("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:t}),null}}const Tg=()=>crypto.randomUUID();function Mg(e,t){const{id:r,projectId:s,branchId:o,mergedBranchId:a,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:u,author:p,metadata:h,files:m,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Tg(),project_id:s??String(t),metadata:h?JSON.stringify(h):void 0,files:m?JSON.stringify(m):void 0,branch_id:o,merged_branch_id:a,author_github_username:p==null?void 0:p.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:u}}async function $g({projectId:e,commits:t}){const r=$e();try{const s=t.reduce((i,l)=>{const{author:c}=l;return c!=null&&c.username&&(c!=null&&c.avatarUrl)&&(i[c.username]=c.avatarUrl),i},{});for(const i in s)await Ag(i,s[i]);const o=t.map(i=>Mg(i,e));return(await r.insertInto("commits").values(o).onConflict(ur(o[0],"id",["created_at"])).returningAll().execute()).map(Fn)}catch(s){return Ie("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(o=>o.id).filter(Boolean)}),[]}}const Fg=()=>crypto.randomUUID();function Rg(e){const{id:t,files:r,branches:s,team:o,analyzedAt:a,contentChangedAt:i,createdAt:l,updatedAt:c,metadata:u,...p}=e;return{...p,id:t??Fg(),analyzed_at:a||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:c||null,metadata:u?JSON.stringify(u):null,github_token:null,configuration:null,team_id:null}}async function Dg(e){try{if(e.length===0)return null;const t=$e(),r=e.map(a=>Rg(a)),s=await t.insertInto("projects").values(r).onConflict(ur(r[0],"id",["created_at"])).returningAll().execute(),o=s==null?void 0:s[0];return o?po(o):null}catch(t){return console.log("Error saving project",t),null}}const Xs=G.join(io.homedir(),".codeyam","secrets.json"),eo=G.join(process.cwd(),".codeyam","secrets.json");async function xn(){let e={};try{if(q.existsSync(eo)){const a=await Pe.readFile(eo,"utf8");e=JSON.parse(a)}}catch{console.warn(Ks.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(q.existsSync(Xs)){const a=await Pe.readFile(Xs,"utf8");e={...JSON.parse(a),...e}}}catch{console.warn(Ks.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 s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(t.GROQ_API_KEY=o),t}async function Ig(e,t=!0){const r=t?Xs:eo,s=G.dirname(r);await Pe.mkdir(s,{recursive:!0}),await Pe.writeFile(r,JSON.stringify(e,null,2)),await Pe.chmod(r,384)}function Og(e=!0){return e?Xs:eo}async function Bl(){const e=await xn(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Lg(e){console.log(),console.log(Ks.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await _m({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function zg(e=!0){const t=await Bl();if(t.isValid)return t.secrets;const r=await Lg(t.missing),o={...await xn(),...r};await Ig(o,e);const a=Og(e);return console.log(Ks.green(`✓ Configuration saved to ${a}`)),(await Bl()).secrets}function Bg(e){const t=G.resolve(e),r=G.parse(t).root;return t===r||t===G.resolve(io.homedir())}function Vd(e=process.cwd()){let t=G.resolve(e);const r=G.parse(t).root;for(;t!==r;){if(Bg(t))return null;const s=G.join(t,".codeyam","config.json");if(q.existsSync(s))return t;t=G.dirname(t)}return null}let Kd=Vd();function Ce(){return Kd}function Yg(e){Kd=e}function Gd(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const Ug={"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>`};Gd(Ug);const Wg={"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>`};Gd(Wg);function Dr(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const o=Array.isArray(e)?e:[],a=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?a[i]=Dr(o[i],l,r):a[i]=l}return a}const s={...e};for(const o in t)if(t[o]===null)s[o]=null;else if(Array.isArray(t[o])){const a=Array.isArray(e[o])?e[o]:[];s[o]=[];for(let i=0;i<t[o].length;i++){const l=t[o][i];typeof l=="object"&&l!==null?s[o][i]=Dr(a[i],l,r):s[o][i]=l}}else typeof t[o]=="object"&&t[o]!==null?s[o]=Dr(s[o]??{},t[o],r):s[o]=t[o];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function Jg({projectId:e,commit:t,branch:r}){var l,c,u,p,h,m,f;let s;const o={commitId:t.id,branchId:r.id,active:!0},a=await vg({projectId:e,commitId:t.id,includeBranches:!0});if(a&&a.length>0){s=(l=a.sort((g,x)=>{var b,v,N,w;return(((v=(b=g.branch.metadata)==null?void 0:b.permanent)==null?void 0:v.order)??999)-(((w=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:l.branch,s&&((u=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:u.order)!==void 0&&(((h=(p=r.metadata)==null?void 0:p.permanent)==null?void 0:h.order)<=((f=(m=s.metadata)==null?void 0:m.permanent)==null?void 0:f.order)?s=r:o.active=!1);const y=a.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await zl(y.map(g=>({...g,active:g.branchId===s.id})))}(a==null?void 0:a.find(y=>y.branchId===o.branchId))||await zl([o])}let Yl=!1;function bn(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=Ce();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function We(){if(!Yl){Yl=!0;const t=Ce();t&&await Vg(t)}const e=await zg();process.env.SQLITE_PATH=bn(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function k_(){try{return await We(),await di({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function De(e){await We();const t=await di({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await ci({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function E_(e){await We();const t=await di({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:Xa(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await Dg([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function __(e){await We();const t=await ci({projectId:e.id,names:["_local"]});if(t&&t.length>0)return{branch:t[0],created:!1};const r={projectId:e.id,name:"_local",ref:"_local",primary:!0,activeAt:new Date().toISOString(),contentChangedAt:new Date().toISOString(),metadata:{contributors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],commits:{total:0,last7Days:[]},timeline:[{title:"Local branch created",date:new Date().toISOString(),authors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],sha:"local-init"}]}},s=await cg([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function Hg(e,t,r){await We();const s=Ce(),o=pg(`${e.slug}-local-${Date.now()}-${Math.random()}`),a=r.map(c=>{let u="";if(s)try{if(u=Me(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!u)try{const p=Me(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(p){const h=p.split(`
|
|
30
|
+
`);u=`@@ -0,0 +1,${h.length} @@
|
|
31
|
+
${h.map(m=>`+${m}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:c,status:"modified",patch:u}}),i={sha:o,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${o}`,htmlUrl:`local://codeyam/${e.slug}/${o}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:a,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await $g({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await Jg({projectId:e.id,commit:l[0],branch:t}),l[0]}async function Vg(e){const t=ee.join(e,".codeyam","db.sqlite3"),r=ee.join(e,".codeyam","config.json");if(q.existsSync(t)||!q.existsSync(r))return!1;const{default:s}=await import("./init-CzFOE1qs.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function zn(){await We();const e=await tt({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const u=`${c.name}::${c.filePath}`,p=t.get(u);(!p||c.createdAt&&p.createdAt&&c.createdAt>p.createdAt)&&t.set(u,c)}const r=[...t.values()],s=e.map(c=>c.sha),o=await gn({entityShas:s,excludeMetadata:!0}),a=new Map;if(o)for(const c of o)a.has(c.entitySha)||a.set(c.entitySha,[]),a.get(c.entitySha).push(c);const i=new Map;for(const c of e){const u=`${c.name}::${c.filePath}`,p=i.get(u)||[];p.push(c.sha),i.set(u,p)}return r.map(c=>{const u=a.get(c.sha)||[];if(u.length>0)return{...c,analyses:u};const p=`${c.name}::${c.filePath}`,h=i.get(p)||[];for(const m of h){if(m===c.sha)continue;const f=a.get(m);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Kg(e){await We();const t=await tt(e);return!t||t.length===0?[]:t.filter(r=>{var s;return!((s=r.metadata)!=null&&s.isSuperseded)})}async function mo(e,t){await We();const r=await gn({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Wd({projectId:r[0].projectId,sha:e});if(s)for(const o of r)o.entity=s}return r||[]}async function fo(e){if(await We(),e.name&&e.projectId){const r=await gn({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(a=>{const i=a.scenarios&&a.scenarios.length>0,l=!e.filePath||a.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((a,i)=>{const l=new Date(a.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const o=r.filter(a=>a.scenarios&&a.scenarios.length>0);if(o.length>0)return o.sort((a,i)=>{const l=new Date(a.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),o[0]}}const t=await gn({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function qd(e){await We();const t=await gn({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function In(e){await We();const t=await Ye();if(!t)return null;const{project:r}=await De(t);return await Wd({projectId:r.id,sha:e})}async function Qd(e){var s,o,a,i,l,c,u,p;await We();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const m of h){if(!m.filePath||!m.name)continue;const f=m.resolvedFilePath??m.filePath,y=m.resolvedName??m.name;let g=await tt({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&m.resolvedIsDefault&&(g=await tt({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],b=await gn({entityShas:[x.sha],limit:1});let v,N,w;if(b&&b.length>0&&b[0].scenarios){const C=b[0],S=C.scenarios||[],k=S.length,T=S.find($=>{var M,R;return(R=(M=$.metadata)==null?void 0:M.screenshotPaths)==null?void 0:R[0]});T&&(v=(a=(o=T.metadata)==null?void 0:o.screenshotPaths)==null?void 0:a[0],N=T.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||C.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:C.createdAt?new Date(C.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...x,screenshotPath:v,scenarioName:N,analysisStatus:w})}}}if((l=e.metadata)!=null&&l.importedBy){const h=[];for(const m in e.metadata.importedBy)for(const f in e.metadata.importedBy[m]){const y=e.metadata.importedBy[m][f];y.shas&&h.push(...y.shas)}if(h.length>0){const m=await tt({projectId:e.projectId,shas:h});if(m)for(const f of m){const y=await gn({entityShas:[f.sha],limit:1});let g,x,b;if(y&&y.length>0&&y[0].scenarios){const v=y[0],N=v.scenarios||[],w=N.length,C=N.find(k=>{var T,_;return(_=(T=k.metadata)==null?void 0:T.screenshotPaths)==null?void 0:_[0]});C&&(g=(u=(c=C.metadata)==null?void 0:c.screenshotPaths)==null?void 0:u[0],x=C.name),b={status:((p=f.metadata)==null?void 0:p.previousVersionWithAnalyses)||v.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:w,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function Ye(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Ae.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function hr(){await We();try{const e=await Ye();if(!e)return null;const{project:t,branch:r}=await De(e),s=await Qs({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function go(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Ae.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Zd(e){try{const t=Ce();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=ee.join(t,e.filePath);return await Ae.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Xd(e){try{const t=Ce();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),o=(await Ae.stat(r)).mtime.getTime(),a=e.updatedAt||e.createdAt;if(!a)return!1;const i=new Date(a).getTime();return o>i+1e3}catch{return!1}}async function eu(e){if(await We(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await tt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await gn({entityShas:r}),o=new Map;if(s)for(const i of s)o.has(i.entitySha)||o.set(i.entitySha,[]),o.get(i.entitySha).push(i);for(const[i,l]of o.entries())l.sort((c,u)=>{const p=new Date(c.createdAt||0).getTime();return new Date(u.createdAt||0).getTime()-p});const a=t.map(i=>({...i,analyses:o.get(i.sha)||[]}));return a.sort((i,l)=>{var p,h;const c=((p=i.analyses[0])==null?void 0:p.createdAt)||i.createdAt||"",u=((h=l.analyses[0])==null?void 0:h.createdAt)||l.createdAt||"";return new Date(u).getTime()-new Date(c).getTime()}),a}async function tu(e){try{const t=Ce();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await Ae.readFile(r,"utf8"),o=JSON.parse(s),a={...o,...e},i=JSON.stringify(a,null,2);if(await Ae.writeFile(r,i,"utf8"),o.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await or({projectSlug:o.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Gg=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:zn,getAnalysesForEntity:mo,getAnalysisForExactEntitySha:qd,getCurrentCommit:hr,getCurrentEntities:Kg,getEntityBySha:In,getEntityCodeFromFilesystem:Zd,getEntityHistory:eu,getLatestAnalysisForEntity:fo,getProjectConfig:go,getProjectSlug:Ye,getRelatedEntities:Qd,hasFileBeenModifiedSinceEntity:Xd,requireBranchAndProject:De,updateProjectConfig:tu},Symbol.toStringTag,{value:"Module"})),nu="secrets.json";function ru(e){return ee.join(e,".codeyam",nu)}function su(){return ee.join(Pa.homedir(),".codeyam",nu)}async function yo(e){let t={};try{const r=su(),s=await Ae.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=ru(e),s=await Ae.readFile(r,"utf-8"),o=JSON.parse(s);t={...t,...o}}catch{}return t}async function qg(e,t,r=!0){const s=r?su():ru(e),o=ee.dirname(s);await Ae.mkdir(o,{recursive:!0}),await Ae.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}async function Qg(e){const t=await yo(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const Zg=3;let Tr=0;async function bs(e){if(!e||e.length===0)return[];if(Tr>=Zg)return console.warn(`[Loader] Circuit breaker open (${Tr} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const o=setTimeout(()=>{s||(s=!0,Tr++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);tt({shas:e,excludeMetadata:!0}).then(a=>{s||(s=!0,clearTimeout(o),Tr=0,r(a||[]))}).catch(()=>{s||(s=!0,clearTimeout(o),Tr++,r([]))})})}function Xg({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(Pt(t))try{if(xm(t).length>0)return!1;Zo(t,{recursive:!0})}catch{return!1}try{Me(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const o of r)if(o.includes("*"))try{Me(`rm -rf "${Yr(t,o)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const a=Yr(t,o);Pt(a)&&Zo(a,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(Pt(t))try{Zo(t,{recursive:!0})}catch{}return!1}}async function e0({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:o=!1,extraArgs:a=[],timeoutMs:i=3e5}){const l=Date.now();if(!s&&a.length===0&&Xg({sourcePath:e,destinationPath:t,excludes:r,silent:o})){if(!o){const u=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${u}s]`)}return}return new Promise((c,u)=>{const p=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...a);for(const x of r)m.push(`--exclude=${x}`);m.push(p,h);const f=kt("rsync",m);let y=!1;const g=i?setTimeout(()=>{if(!y){y=!0,f.kill("SIGKILL");const x=((Date.now()-l)/1e3).toFixed(1);u(new Error(`rsync timed out after ${x}s syncing ${e} → ${t}`))}},i):void 0;f.on("exit",x=>{if(!y)if(y=!0,g&&clearTimeout(g),x===0){if(!o){const b=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${b}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${x}`,JSON.stringify({rsyncArgs:m},null,2)),u(new Error(`rsync failed with exit code ${x}`))}),f.on("error",x=>{y||(y=!0,g&&clearTimeout(g),o||console.log("Error occurred:",x),u(x))})})}const t0=ti(ei);async function n0(e){return new Promise(t=>setTimeout(t,e))}function r0(e){try{return process.kill(e,0),!0}catch{return!1}}async function ou(e){try{const{stdout:t}=await t0(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
+
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),s=[...r];for(const o of r){const a=await ou(o);s.push(...a)}return s}catch{return[]}}function Ul(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function s0(e,t,r){const s=await ou(e);for(const o of s.reverse())await Ul(o,t,r);await Ul(e,t,r)}async function Ur(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function o(a,i){await s0(e,a,t);for(let l=0;l<i;l++)if(await n0(1e3),s+=1e3,!await r0(e))return t(`Process tree ${e} successfully killed with ${a} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${a}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let a=0;a<r;a++)if(await o("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function o0(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:zm(),createdAt:t}}Pm.config({quiet:!0});var au=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(au||{});class a0 extends Am{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Tm(),{process:s,type:o,name:a,metadata:i,parentId:l}=t,c={id:r,type:o,name:a,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:c,process:s}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const u=(h,m)=>{this.handleProcessExit(r,h,m)},p=h=>{this.handleProcessError(r,h)};return s.on("exit",u),s.on("error",p),s.__cleanup=()=>{s.removeListener("exit",u),s.removeListener("error",p)},this.emit("processStarted",c),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 s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:o,process:a}=s;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(r.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(l=>this.shutdown(l,r))),a.pid)try{await Ur(a.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=a.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(o=>this.shutdown(o.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[o,a]of this.processes.entries()){const{info:i}=a;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=a.process.__cleanup;l&&l(),this.processes.delete(o)}}}handleProcessExit(t,r,s){const o=this.processes.get(t);if(!o)return;const{info:a}=o;a.endedAt=Date.now(),a.exitCode=r,a.signal=s,r===0?a.state="completed":s?a.state="killed":a.state="failed",this.emit("processExited",a)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:r.message},this.emit("processExited",o)}}let oa=null;function i0(){return oa||(oa=new a0),oa}const l0={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function c0({command:e,args:t,workingDir:r,outputOptions:s=l0,processName:o,env:a}){const i={...process.env,...a||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},l=kt(e,t,{cwd:r,env:i});return i0().register({process:l,type:au.Other,name:o,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(p=>{const h=f=>{const y=ee.join(r,"log.txt");q.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},m=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
+
`).map(b=>b.trim()?`[${g}]${y} ${b}`:b).join(`
|
|
36
|
+
`)};l.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&h(g+`
|
|
37
|
+
`),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&h(g+`
|
|
38
|
+
`),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){p(f)})}),process:l}}function d0(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function u0({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const o=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
+
`);q.writeFileSync(`${e}/.env`,o);const a=d0(r);return c0({command:"node",args:["--enable-source-maps","./dist/project/start.js",...a],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const p0="/tmp/codeyam/local-dev";function iu(e){return G.join(p0,e)}function lu(e){return G.join(iu(e),"codeyam")}function Lt(e){return G.join(iu(e),"project")}function Qr(e){return G.join(lu(e),"log.txt")}const h0=[".sync-metadata.json","__codeyamMocks__"];async function m0(e,t={}){const{port:r,silent:s=!0}=t,o=Lt(e);if(r)try{Me(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${o}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(a=>setTimeout(a,500))}async function f0(e,t={}){const{killProcesses:r=!0,port:s,silent:o=!0}=t,a=Lt(e),i=[],l=[];if(!q.existsSync(a))return{removed:i,errors:l};r&&await m0(e,{port:s,silent:o});for(const c of h0){const u=G.join(a,c);if(q.existsSync(u))try{(await Pe.stat(u)).isDirectory()?await Pe.rm(u,{recursive:!0,force:!0}):await Pe.unlink(u),i.push(c)}catch(p){l.push(`${c}: ${p instanceof Error?p.message:String(p)}`)}}return{removed:i,errors:l}}const g0=G.dirname(lo(import.meta.url));function y0(e){let t=e;for(;t!==G.dirname(t);){const r=G.join(t,"package.json");if(q.existsSync(r))try{if(JSON.parse(q.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=G.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function xo(){const e=y0(g0);return G.join(e,"analyzer-template")}function mr(e){return lu(e)}function x0(){const e=xo();return q.existsSync(G.join(e,".finalized"))}async function Wl(e){const t=xo(),r=mr(e),s=Date.now(),o=()=>`${((Date.now()-s)/1e3).toFixed(1)}s`;if(!q.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Pe.mkdir(G.dirname(r),{recursive:!0}),console.log(`[createAnalyzer] Starting rsync: ${t} → ${r}`),await e0({sourcePath:t,destinationPath:r,silent:!0}),console.log(`[createAnalyzer] rsync completed (${o()})`),q.existsSync(G.join(r,"dist"))||(console.warn("[createAnalyzer] WARNING: dist/ not found after rsync — template may not be built. Attempting build..."),Me("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5}),console.log(`[createAnalyzer] npm install + build completed (${o()})`)),console.log(`[createAnalyzer] Done (${o()})`)}function fr(e,t,r,s){const o=mr(e);if(!q.existsSync(o))throw new Error(`Analyzer not found at ${o}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const a=void 0;return u0({absoluteCodeyamRootPath:o,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:a,stderrToConsole:!1,stderrToFile:!0,stderrCallback:a}})}function b0(e){const t=xo(),r=mr(e),s=G.join(t,".build-info.json"),o=G.join(r,".build-info.json");if(!q.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!q.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!q.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const a=JSON.parse(q.readFileSync(s,"utf8")),i=JSON.parse(q.readFileSync(o,"utf8"));return a.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${a.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(a){return{isFresh:!1,reason:`Error reading build markers: ${a.message}`}}}async function Zr(e,t){const r=mr(e);if(!q.existsSync(r)){t.update("Creating analyzer..."),await Wl(e);return}const s=b0(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Wl(e),t.update("Analyzer updated"))}async function ui(e){await f0(e,{killProcesses:!1})}const v0=G.dirname(lo(import.meta.url));function bo(){let e=v0;for(;e!==G.dirname(e);){const t=G.join(e,"package.json");if(q.existsSync(t))try{if(JSON.parse(q.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=G.dirname(e)}return null}function rr(e){if(!q.existsSync(e))return null;try{return JSON.parse(q.readFileSync(e,"utf8"))}catch{return null}}function w0(){const e=bo();if(e){const t=[G.join(e,"src/webserver/build-info.json"),G.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=rr(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function N0(){const e=bo();if(e){const t=G.join(e,"package.json");try{const r=JSON.parse(q.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const pi=w0(),aa=N0();function hi(){if(aa!=="unknown"&&aa!=="0.1.0")return aa;const e=bo();if(e)for(const t of[G.join(e,"src/webserver/build-info.json"),G.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=rr(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function cu(e){const t=bo();let r=null;if(t){const c=[G.join(t,"src/webserver/build-info.json"),G.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const u of c)if(r=rr(u),r)break}const s=xo(),o=G.join(s,".build-info.json"),a=rr(o);let i=null;if(e){const c=mr(e),u=G.join(c,".build-info.json");i=rr(u)}let l=!1;return a&&i?l=a.buildTime>i.buildTime:a&&!i&&e&&(l=!0),{cliVersion:pi,webserverVersion:r,templateVersion:a,cachedAnalyzerVersion:i,isCacheStale:l}}function vo(e){const t=mr(e),r=G.join(t,".build-info.json"),s=rr(r);return(s==null?void 0:s.version)??null}function mi(){const e=Ce();return e?G.join(e,".codeyam","server.json"):null}function j_(e){const t=mi();t&&q.writeFileSync(t,JSON.stringify(e,null,2))}function wo(){const e=mi();if(!e||!q.existsSync(e))return null;try{const t=q.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function fi(){const e=mi();if(e)try{q.unlinkSync(e)}catch{}}function du(e){try{return process.kill(e,0),!0}catch{return!1}}function uu(){try{const e=process.platform==="win32",r=Me(e?'tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH':"ps aux | grep codeyam-server | grep -v grep",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!r)return[];const s=[];if(e)for(const o of r.split(`
|
|
40
|
+
`)){const a=o.match(/"[^"]*","(\d+)"/);if(a){const i=parseInt(a[1],10);if(!isNaN(i))try{Me(`wmic process where "ProcessId=${i}" get CommandLine /FORMAT:LIST`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("codeyam-server")&&s.push(i)}catch{}}}else for(const o of r.split(`
|
|
41
|
+
`)){const a=o.trim().split(/\s+/);if(a.length>=2){const i=parseInt(a[1],10);isNaN(i)||s.push(i)}}return s}catch{return[]}}function P_(){const e=wo();if(e)if(!du(e.pid))fi();else return{running:!0,state:e};const t=uu();return t.length>0?{running:!0,pids:t}:{running:!1}}function S0(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(o=>du(o)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function A_(){let e=!1;const t=[],r=wo();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}fi()}const s=uu();for(const o of s)try{process.kill(o,"SIGTERM"),t.includes(o)||t.push(o),e=!0}catch{}return S0(t),e}function T_(e,t,r=10,s=10){if(t(e))return e;for(let o=1;o<=s;o++){const a=e+o*r;if(t(a))return a}throw new Error(`Could not find a free port starting from ${e} (tried ${s} candidates)`)}function M_(e){try{return Me(`lsof -ti:${e}`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}),!1}catch{return!0}}const C0="/assets/globals-D4iGjX2m.css";function Jl({text:e,subtext:t,linkText:r,linkTo:s}){const[o,a]=P(!1);return o?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("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"})})}),d("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(ke,{to:s,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:()=>a(!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 k0({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:d("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),d("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function E0({serverVersion:e}){const[t,r]=P("stale"),[s,o]=P(null),a=async()=>{r("restarting"),o(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const c=30,u=1e3,p=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?setTimeout(()=>void p(),u):(o("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void p(),500)}catch(i){o(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:d("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"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(ve,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),d("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."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&d(ve,{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"&&d(ve,{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 a(),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")&&d("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[d("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 xt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:o=2e3,ariaLabel:a,icon:i=!1,iconSize:l=14}){const[c,u]=P(!1),p=ce(()=>{navigator.clipboard.writeText(e).then(()=>{u(!0),setTimeout(()=>u(!1),o)}).catch(h=>{console.error("Failed to copy:",h)})},[e,o]);return n("button",{onClick:p,className:`cursor-pointer ${s}`,disabled:c,"aria-label":a||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(Mt,{size:l,className:"text-green-500"}):n(Ot,{size:l}):c?r:t})}function _0({currentVersion:e,latestVersion:t}){const[r,s]=P(!1);if(r)return null;const o="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),d("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),d("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:o}),n(xt,{content:o,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Mr=null,vs=0;const j0=3600*1e3;function P0(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let o=0;o<Math.max(r.length,s.length);o++){const a=r[o]??0,i=s[o]??0;if(isNaN(a)||isNaN(i))return!1;if(a>i)return!0;if(a<i)return!1}return!1}async function A0(){const e=hi();if(Mr&&Date.now()-vs<j0)return Mr;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Mr=l,vs=Date.now(),l}const a=(await s.json()).version;if(!a){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Mr=l,vs=Date.now(),l}const i={updateAvailable:P0(a,e),latestVersion:a,currentVersion:e};return Mr=i,vs=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function to(e){return G.join(e,".codeyam","queue.json")}function Ir(e){const t=to(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 T0(e,t){const r=to(e),s=G.dirname(r);q.existsSync(s)||q.mkdirSync(s,{recursive:!0});try{q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}const oo=class oo extends Gr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=de.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||oo.IGNORED_DIRS.some(o=>r.includes(o+"/")||r.includes(o+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!de.existsSync(r)){de.existsSync(s)&&(de.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const o=ee.dirname(s);de.existsSync(o)||de.mkdirSync(o,{recursive:!0}),de.copyFileSync(r,s);const a=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:a,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(o){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,o);const a={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",a)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};oo.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Ta=oo,M0=class extends Gr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const Ma="__codeyam_dev_mode_event_emitter__";globalThis[Ma]||(globalThis[Ma]=new M0);const Hl=globalThis[Ma],$a=new Map;async function $0(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await F0(e,t,r);else if(e.type==="baseline")await R0(e,t,r);else if(e.type==="recapture")await D0(e,t,r);else if(e.type==="capture-only")await I0(e,t,r);else if(e.type==="debug-setup")await O0(e,t,r);else if(e.type==="interactive-start")await L0(e,t,r);else if(e.type==="interactive-stop")await z0(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function F0(e,t,r){var b,v,N,w;const{projectSlug:s,commitSha:o,entityShas:a}=e;if(!o)throw new Error("Analysis job missing commitSha");const i=a||[],l=e.onlyDataStructure,c=Qr(s),u=C=>{const S=`CodeYam Log Level 1: ${C}`;console.log(`[Queue] ${C}`);try{q.mkdirSync(G.dirname(c),{recursive:!0}),q.appendFileSync(c,`[${new Date().toLocaleString()}] ${S}
|
|
42
|
+
|
|
43
|
+
`)}catch{}},{project:p}=await De(s);u("Preparing project cache..."),await ui(s),u("Preparing simulation engine..."),await Zr(s,{update:C=>u(C)});const h=vo(s),m={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),...!l&&i.length>0?{ENTITY_SHAS:i.join(",")}:{},...l?{ONLY_DATA_STRUCTURE:"true"}:{},...h?{ANALYZER_VERSION:h}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},f=(v=(b=p.metadata)==null?void 0:b.webapps)==null?void 0:v[0];if(!f)throw new Error("No webapps found in project metadata");const y={packageManager:((N=p.metadata)==null?void 0:N.packageManager)||"npm",absoluteProjectRootPath:Lt(s),port:0,noServer:!0,framework:f.framework,...l?{}:{orchestrateCapture:"local-sequential"}},g=fr(s,m,y),x=C=>{try{return process.kill(C,0),!0}catch{return!1}};await pn({commitSha:o,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((w=e.filePaths)==null?void 0:w.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:g.process.pid}}),r==null||r.notifyChange("commit");try{try{const C=new Promise((S,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([g.promise,C]),await pn({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await pn({commitSha:o,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(S=>setTimeout(S,2e3))}finally{if(g.process.pid)try{x(g.process.pid)&&await Ur(g.process.pid,()=>{})}catch{}}}catch(C){if(console.error(`[Queue] Analysis job ${e.id} failed:`,C),g.process.pid&&x(g.process.pid))try{await Ur(g.process.pid,()=>{})}catch{}try{await pn({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:C instanceof Error?C.message:String(C)}}),r==null||r.notifyChange("commit")}catch(S){console.error("[Queue] Failed to update commit metadata after job failure:",S)}throw C}}async function R0(e,t,r){var m,f,y;const{projectSlug:s,commitSha:o}=e;if(!o)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:a}=await De(s);await ui(s),await Zr(s,{update:g=>console.log(`[Queue] ${g}`)});const i=vo(s),l={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(m=a.metadata)==null?void 0:m.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const u={packageManager:((y=a.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:Lt(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},p=fr(s,l,u),h=g=>{try{return process.kill(g,0),!0}catch{return!1}};await pn({commitSha:o,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:p.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,b)=>setTimeout(()=>b(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([p.promise,g]),await pn({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(p.process.pid)try{h(p.process.pid)&&await Ur(p.process.pid,()=>{})}catch{}}}async function D0(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:o,scenarioId:a,defaultWidth:i}=e;if(!o)throw new Error("Recapture job missing analysisId");const l=await Xt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:b}=await import("./index-DRb-tJ77.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await pr(o,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!a||v.name===a)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:c}=await De(s);await Zr(s,{update:b=>console.log(`[Queue] ${b}`)});const u=vo(s),p={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,...a?{SCENARIO_IDS:a}:{},...u?{ANALYZER_VERSION:u}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:Lt(s),port:void 0,noServer:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??st.Next,orchestrateCapture:"local-sequential"},m=fr(s,p,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function I0(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:o,scenarioId:a,defaultWidth:i}=e;if(!o)throw new Error("Capture-only job missing analysisId");const l=await Xt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:b}=await import("./index-DRb-tJ77.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await pr(o,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!a||v.name===a)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:c}=await De(s);await Zr(s,{update:b=>console.log(`[Queue] ${b}`)});const u=vo(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const p={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:o,...a?{SCENARIO_IDS:a}:{},...u?{ANALYZER_VERSION:u}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:Lt(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??st.Next,orchestrateCapture:"local-sequential"},m=fr(s,p,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function O0(e,t,r){var m,f,y,g;const{projectSlug:s,analysisId:o,scenarioId:a}=e;if(!o)throw new Error("Debug setup job missing analysisId");const i=await Xt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await De(s);await ui(s),await Zr(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,PREP_ONLY:"true"};a&&(c.SCENARIO_IDS=a);const u={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:Lt(s),port:void 0,noServer:!1,framework:((g=(y=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||st.Next},h=await fr(s,c,u).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function L0(e,t,r){var x,b,v,N;const{projectSlug:s,analysisId:o,scenarioId:a}=e;if(!o)throw new Error("Interactive start job missing analysisId");const i=await Xt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await De(s),c={...await xn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:bn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,INTERACTIVE_MODE:"true"};a&&(c.INITIAL_SCENARIO_ID=a),i.scenarios&&i.scenarios.length>0&&(c.SCENARIO_IDS=i.scenarios.map(w=>w.id).join(","));const u=Lt(s),p=ee.join(u,".next","dev","lock");if(de.existsSync(p)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const w=Me(`pgrep -f ${JSON.stringify(u)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(w)for(const C of w.split(`
|
|
44
|
+
`).filter(Boolean))try{process.kill(parseInt(C,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${C}`)}catch{}}catch{}try{de.unlinkSync(p),console.log("[Queue] Removed stale lock file")}catch{}}const h=de.existsSync(u)&&de.existsSync(ee.join(u,"package.json")),m={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:u,port:void 0,noServer:!1,fast:h,framework:((N=(v=(b=l.metadata)==null?void 0:b.webapps)==null?void 0:v[0])==null?void 0:N.framework)||st.Next};await pr(o,w=>{w.readyToBeCaptured=!0});const f=fr(s,c,m);await Hd(o,w=>{w.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${o}, PID: ${f.process.pid}`);const y=Lt(s),g=new Ta({projectRootPath:t,tmpProjectPath:y});g.on("sync",w=>{w.type==="file-synced"?Hl.emitFileSynced(w.fileName,w.filePath):w.type==="error"&&Hl.emitError(w.fileName,w.filePath)}),g.start(),$a.set(o,g),console.log(`[Queue] File sync watcher started for analysis ${o}`)}async function z0(e,t,r){var u;const{projectSlug:s,analysisId:o}=e;if(!o)throw new Error("Interactive stop job missing analysisId");const a=await Xt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${o} not found`);const i=(u=a.metadata)==null?void 0:u.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${o}`);return}const l=$a.get(o);l&&(l.stop(),$a.delete(o),console.log(`[Queue] File sync watcher stopped for analysis ${o}`));const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${o}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Ur(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(p){throw console.error(`[Queue] Failed to kill process ${c}:`,p),p}finally{await Hd(o,p=>{p.interactiveMode=null})}}class B0{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=Ir(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||Xa(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const o=new Promise((a,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):a()})});return this.state.paused||this.processNext().catch(a=>{console.error("[Queue] ERROR in processNext():",a)}),{jobId:r,completion:o}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(o=>o.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const o=this.completionCallbacks.get(t);o&&(setImmediate(()=>o(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(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 s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const o=r==="up"?s-1:s+1;if(o<0||o>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const a=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[o],this.state.jobs[o]=a,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${o})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await $0(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 s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){T0(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Y0{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=to(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=to(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=q.watch(r,(s,o)=>{o==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}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 U0{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Ir(r)}start(){this.cachedState=Ir(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 Y0(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const o=new Promise((i,l)=>{r=i,s=l}),a=`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),s(i)}),{jobId:a,completion:o}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}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 s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Ir(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Ir(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function W0(e){const t=G.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 J0(e){try{return process.kill(e,0),!0}catch{return!1}}async function H0(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function V0(e){const t=W0(e);return!t||!J0(t.pid)||!await H0(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class K0 extends Gr{constructor(){super();vt(this,"watcher",null);vt(this,"dbPath",null);vt(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=bn();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",o=>{const a=Date.now(),i=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${o}`),console.log(`[dbNotifier] Timestamp: ${i} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:a})}).on("error",o=>{console.error("Database watcher error:",o),this.emit("error",o)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),o=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${o} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Nt=new K0;let Mn=null,Or=null;async function G0(){if(!Mn){if(Or){await Or;return}Or=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Vd()||process.cwd();if(Yg(e),console.log(`[GlobalQueue] Project root: ${e}`),await We(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),o=JSON.parse(await de.promises.readFile(r,"utf8")).projectSlug;o&&(await or({projectSlug:o,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await V0(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new U0(t,e,()=>{Nt.notifyChange("unknown")});await r.start(),Mn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new B0(e,Nt);await r.start(),Mn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Or}}async function en(){return Mn||await G0(),Mn}function q0(){return Mn||(Or&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const Q0=()=>[{rel:"stylesheet",href:C0},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],Z0={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:hi()};async function X0({request:e,context:t}){var r,s,o,a,i,l,c,u,p,h,m;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=Ce()||process.cwd(),[x,b,v]=await Promise.all([Ye(),yo(g),A0().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:w}=await De(x);y();const C=await Qs({projectId:N.id,branchId:w.id,limit:20,skipRelations:!0});y();const S=C.length>0?C[0]:null,k=t.analysisQueue||q0(),T=k==null?void 0:k.getState();y();const _=await Promise.all(((T==null?void 0:T.jobs)||[]).map(async H=>{var oe;const ne=await bs(H.entityShas||[]);return ne.length===0&&((oe=H.entityShas)!=null&&oe.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",H.id),{...H,entities:ne}}));let $=null;if(T!=null&&T.currentlyExecuting){const H=T.currentlyExecuting,ne=await bs(H.entityShas||[]);ne.length===0&&((r=H.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",H.id),$={...H,entities:ne}}const M=$?_.filter(H=>H.id!==$.id):_;let R=((o=(s=S==null?void 0:S.metadata)==null?void 0:s.currentRun)==null?void 0:o.currentEntityShas)||[];if(R.length===0){const H=((a=S==null?void 0:S.metadata)==null?void 0:a.historicalRuns)||[];if(H.length>0){const oe=[...H].sort((Z,re)=>{const ue=Z.archivedAt||Z.createdAt||"";return(re.archivedAt||re.createdAt||"").localeCompare(ue)})[0];if(oe){const Z=oe.analysisCompletedAt||oe.createdAt;if(Z){const re=new Date(Z).getTime(),we=Date.now()-1440*60*1e3;re>we&&(R=oe.currentEntityShas||[])}}}}const z=await bs(R),O=[];b.ANTHROPIC_API_KEY&&O.push("ANTHROPIC_API_KEY"),b.GROQ_API_KEY&&O.push("GROQ_API_KEY"),b.OPENAI_API_KEY&&O.push("OPENAI_API_KEY"),b.OPENROUTER_API_KEY&&O.push("OPENROUTER_API_KEY"),y();const U=[];for(const H of C){const ne=((i=H.metadata)==null?void 0:i.historicalRuns)||[];for(const oe of ne)U.push(oe)}U.sort((H,ne)=>{const oe=H.archivedAt||H.analysisCompletedAt||H.createdAt||"";return(ne.archivedAt||ne.analysisCompletedAt||ne.createdAt||"").localeCompare(oe)});const W=new Set(((l=$==null?void 0:$.entities)==null?void 0:l.map(H=>H.sha))||[]),j=U.filter(H=>!(H.currentEntityShas||[]).some(oe=>W.has(oe))).slice(0,3),D=new Set;for(const H of j)for(const ne of H.currentEntityShas||[])D.add(ne);const A=await bs(Array.from(D)),L=new Map;for(const H of A)L.set(H.sha,H);const E=j.map(H=>({...H,entities:(H.currentEntityShas||[]).map(ne=>L.get(ne)).filter(ne=>ne!=null)})),F=wo(),I=(F==null?void 0:F.cliVersion)??"unknown",K=I!=="unknown"&&I!==pi,Q=((u=(c=N.metadata)==null?void 0:c.labs)==null?void 0:u.simulations)??!1,V=Q?x0():!1,Y=((p=N.metadata)==null?void 0:p.editorMode)??!1,B={currentRun:(h=S==null?void 0:S.metadata)==null?void 0:h.currentRun,projectSlug:x,currentEntities:z,availableAPIKeys:O,queuedJobCount:M.length,queueJobs:M,currentlyExecuting:$,historicalRuns:E,isServerOutOfDate:K,serverVersion:I,npmUpdate:v!=null&&v.updateAvailable&&v.latestVersion?{latestVersion:v.latestVersion,currentVersion:v.currentVersion}:null,labs:((m=N.metadata)==null?void 0:m.labs)??null,simulationsEnabled:Q,isSimulationsReady:V,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:Y,displayVersion:hi()};return le(B)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),le(Z0)}}function ey(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:o,queueJobs:a,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:u,npmUpdate:p,labs:h,simulationsEnabled:m,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=lt(),{toasts:b,closeToast:v}=ai(),N=Bt(),w=ye(N),C=Vr(),S=ye(C.pathname);se(()=>{w.current=N},[N]),se(()=>{S.current=C.pathname},[C.pathname]);const k=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/")||C.pathname.startsWith("/editor"),T=C.pathname.includes("/fullscreen")||C.pathname.startsWith("/editor");return se(()=>{let _=null,$=null,M=0;function R(){_||(_=new EventSource("/api/events"),_.addEventListener("message",U=>{const W=JSON.parse(U.data);(W.type==="queue"||W.type==="db-change")&&W.type;const J=Km(S.current),j=Gm({now:Date.now(),lastRevalidation:M,throttleMs:J});j==="immediate"?(w.current.revalidate(),M=Date.now()):($&&clearTimeout($),$=setTimeout(()=>{w.current.revalidate(),M=Date.now(),$=null},j.delayMs))}),_.addEventListener("error",()=>{}))}function z(){$&&(clearTimeout($),$=null),_&&(_.close(),_=null)}function O(){document.hidden?z():(R(),w.current.revalidate())}return document.hidden||R(),document.addEventListener("visibilitychange",O),()=>{document.removeEventListener("visibilitychange",O),z()}},[]),d(ve,{children:[d("div",{className:`min-h-screen ${k?"":"grid"} bg-cygray-10`,style:k?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!k&&n(tf,{labs:h,isAdmin:y,editorMode:g}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(E0,{serverVersion:u}),p&&p.currentVersion&&n(_0,{currentVersion:p.currentVersion,latestVersion:p.latestVersion}),m&&!g&&s.length===0&&n(Jl,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),m&&!g&&!f&&n(Jl,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(Sd,{})}),n(k0,{version:x})]})]}),n(sf,{toasts:b,onClose:v}),!T&&m&&n(of,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:a,currentlyExecuting:i,historicalRuns:l})]})}const ty=nt(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(jh,{}),n(Ph,{})]}),d("body",{children:[n(nf,{children:n(Xm,{children:n(ey,{})})}),n(Ah,{}),n(Th,{})]})]})});function ny(e){if(e instanceof TypeError&&/fetch/i.test(e.message)||e instanceof Error&&/fetch/i.test(e.message))return!0;const t=String(e);return/failed to fetch|fetch.*failed|load.*chunk/i.test(t)}const ry=Mh(function(){const t=$h(),r=!qo(t)&&ny(t),s=qo(t)?t.status:500,o=qo(t)?t.statusText||"Server Error":"Something went wrong";return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),d("title",{children:[s," - CodeYam"]})]}),n("body",{style:{margin:0,fontFamily:'"IBM Plex Sans", system-ui, -apple-system, sans-serif',backgroundColor:"#1e1e1e",color:"#ffffff",minHeight:"100vh",display:"flex",alignItems:"center"},children:d("div",{style:{maxWidth:700,width:"100%",padding:"64px 80px"},children:[d("div",{style:{fontFamily:'"IBM Plex Mono", monospace',fontSize:32,fontWeight:400,color:"#8E8E8E",lineHeight:1,marginBottom:12},children:["<",s,">"]}),n("h1",{style:{fontSize:42,fontWeight:600,margin:"0 0 20px",color:"#ffffff",lineHeight:1.2},children:r?"Something went wrong :(":o}),r?d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"It looks like the CodeYam server is no longer running. This usually happens when the terminal session that started it was closed."}),d("p",{style:{fontSize:16,color:"#ffffff",margin:0,lineHeight:1.7,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["Run"," ",d("button",{id:"copy-cmd-btn",type:"button",style:{display:"inline-flex",alignItems:"center",gap:8,backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:6,padding:"6px 12px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#ffffff",letterSpacing:"0.05em",textTransform:"uppercase",cursor:"pointer",minWidth:172,justifyContent:"center"},children:[n("span",{id:"copy-cmd-label",children:"codeyam editor"}),d("svg",{id:"copy-cmd-icon",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})," ","in your project directory to restart the server. Then refresh this page."]}),n("script",{dangerouslySetInnerHTML:{__html:`
|
|
45
|
+
document.getElementById('copy-cmd-btn').addEventListener('click', function() {
|
|
46
|
+
var label = document.getElementById('copy-cmd-label');
|
|
47
|
+
var icon = document.getElementById('copy-cmd-icon');
|
|
48
|
+
navigator.clipboard.writeText('codeyam editor').then(function() {
|
|
49
|
+
label.textContent = 'copied!';
|
|
50
|
+
icon.style.display = 'none';
|
|
51
|
+
setTimeout(function() {
|
|
52
|
+
label.textContent = 'codeyam editor';
|
|
53
|
+
icon.style.display = '';
|
|
54
|
+
}, 2000);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
`}})]}):d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"An unexpected error occurred. Try refreshing the page."}),t instanceof Error&&t.message&&n("pre",{style:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:8,padding:"16px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#8E8E8E",textAlign:"left",overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t.message})]})]})})]})}),sy=Object.freeze(Object.defineProperty({__proto__:null,ErrorBoundary:ry,default:ty,links:Q0,loader:X0},Symbol.toStringTag,{value:"Module"}));function ws(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}async function Vl(e,t){try{await fetch("/api/interactive-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,scenarioName:t})})}catch(r){console.error("[useInteractiveMode] Failed to seed scenario:",r)}}function Bn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,enabled:a=!0,refreshTrigger:i=0}){const l=Ke(),[c,u]=P(null),[p,h]=P(!1),[m,f]=P(!1),[y,g]=P(!1),x=ye(!1),b=ye(void 0),v=ye(null),N=ye(null),w=ye(null),C=ye(null),[S,k]=P(0),[T,_]=P(0),$=ye(null),M=ye(!1),R=ye(!1),z=ye(r),{interactiveUrl:O,scenarioUrlMap:U,resetLogs:W}=Qt(o,a),J=ye(t);se(()=>{z.current=r},[r]);const j=ye(i);se(()=>{j.current!==i&&(j.current=i,c&&(f(!0),g(!1),k(0),_(E=>E+1),M.current=!1,R.current=!1,$.current&&(clearTimeout($.current),$.current=null)))},[i,c]),se(()=>{if(J.current===t||(J.current=t,!c||!t))return;f(!0),g(!1),k(0),M.current=!1,R.current=!1,z.current=r,$.current&&(clearTimeout($.current),$.current=null),(async()=>{await Vl(t,r);const F=v.current;let I;if(F&&F[t])I=F[t]+"?width=600px";else if(N.current&&w.current&&r){if(I=N.current,C.current&&s){const V=ws(C.current),Y=ws(s);V!==Y&&(I=I.replace(V,Y))}const K=ws(w.current),Q=ws(r);I=I.replace(K,Q)}else I=c;u(I),_(K=>K+1)})()},[t,r,s,c]),se(()=>{if(O){const E=O+"?width=600px";U&&(v.current=U),N.current=E,r&&(w.current=r),s&&(C.current=s),h(!1),f(!0),(async()=>{t&&r&&await Vl(t,r);const I=v.current,K=t&&I&&I[t]?I[t]+"?width=600px":E;u(K)})()}},[O]);const D=()=>{g(!0),b.current=t;const E=z.current;requestAnimationFrame(()=>{requestAnimationFrame(()=>{z.current===E&&f(!1)})})};se(()=>{const E=F=>{if(F.data.type==="codeyam-resize"){if(F.data.name&&z.current&&F.data.name!==z.current)return;M.current||(M.current=!0,$.current&&(clearTimeout($.current),$.current=null),k(0),R.current&&D())}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]);const A=()=>{if(R.current=!0,M.current){D();return}$.current&&clearTimeout($.current);const E=300*Math.pow(2,S);$.current=setTimeout(()=>{M.current||(S<2?(k(F=>F+1),_(F=>F+1),f(!0),R.current=!1):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),D()))},E)};se(()=>{a&&!x.current&&t&&e&&(x.current=!0,h(!0),g(!1),u(null),(async()=>{if(o)try{await fetch(`/api/logs/${o}`,{method:"DELETE"})}catch(F){console.error("[useInteractiveMode] Failed to clear log file:",F)}W(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[a,t,e,W,o]),se(()=>{const E=e,F=()=>{if(x.current&&E){const K=new URLSearchParams({action:"stop",analysisId:E});navigator.sendBeacon("/api/interactive-mode",K)||fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:K,keepalive:!0}).catch(V=>console.error("Failed to stop interactive mode:",V))}},I=()=>{F()};return window.addEventListener("beforeunload",I),()=>{window.removeEventListener("beforeunload",I),F()}},[e]);const L=y&&b.current===t;return{interactiveServerUrl:c,isStarting:p,isLoading:m,showIframe:L,iframeKey:T,onIframeLoad:A}}const Ns=10,oy=1024;function gi({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:o,hideLabel:a=!1,lightMode:i=!1}){const[l,c]=P(null),u=ye(null),p=pe(()=>[...s].sort((v,N)=>v.width-N.width),[s]),{fittingPresets:h,overflowPresets:m}=pe(()=>{const v=[],N=[];for(const w of p)w.width<=oy?v.push(w):N.push(w);return N.sort((w,C)=>C.width-w.width),{fittingPresets:v,overflowPresets:N}},[p]),f=ce(v=>{if(!u.current)return null;const N=u.current.getBoundingClientRect(),w=v-N.left,C=N.width,S=C/2,T=(h.length>0?h[h.length-1].width:0)/2,_=S-T,$=S+T,M=m.length>0?(m.length-1)*Ns:0;if(m.length>0){if(w<_){if(w<=M){const z=Math.min(Math.floor(w/Ns),m.length-1);return m[z]}return m[m.length-1]}if(w>$){const z=C-w;if(z<=M){const O=Math.min(Math.floor(z/Ns),m.length-1);return m[O]}return m[m.length-1]}}const R=Math.abs(w-S);for(let z=h.length-1;z>=0;z--){const O=h[z],U=h[z-1],W=O.width/2,J=U?U.width/2:0;if(R<=W&&R>=J)return O}return h[0]||m[m.length-1]||null},[h,m]),y=ce(v=>{const N=f(v.clientX);c(N),o==null||o(N)},[f,o]),g=ce(()=>{c(null),o==null||o(null)},[o]),x=ce(v=>{const N=f(v.clientX);N&&r(N)},[f,r]),b=l||{name:t,width:e};return d("div",{ref:u,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(v=>{const N=v.width===e,w=(l==null?void 0:l.name)===v.name,C=v.width/2;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((v,N)=>{const w=N*Ns,C=v.width===e,S=(l==null?void 0:l.name)===v.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||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:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),!a&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:d("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function ay({currentWidth:e,currentHeight:t,devicePresets:r,customSizes:s,onApply:o,onSave:a,onRemove:i,onClose:l}){const[c,u]=P(String(e)),[p,h]=P(String(t)),[m,f]=P(""),[y,g]=P(!1),x=ye(null),b=ye(null);se(()=>{const _=$=>{x.current&&!x.current.contains($.target)&&l()};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[l]),se(()=>{const _=$=>{$.key==="Escape"&&l()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[l]),se(()=>{var _;(_=b.current)==null||_.select()},[]);const v=parseInt(c,10),N=parseInt(p,10),w=v>0&&N>0,C=w&&(v!==e||N!==t),S=()=>{w&&(o({name:"Custom",width:v,height:N}),l())},k=()=>{const _=m.trim();!_||!w||(a(_,v,N),o({name:_,width:v,height:N}),l())},T=_=>{_.key==="Enter"&&(y&&m.trim()?k():C&&S())};return d("div",{ref:x,className:"absolute top-full mt-1 right-0 bg-[#2a2a2a] border border-[#444] rounded-lg shadow-xl z-50 w-64",children:[r&&r.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Presets"}),r.map(_=>d("button",{onClick:()=>{o(_),l()},className:`w-full px-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${_.width===e&&_.height===t?"text-white bg-[#444]":"text-gray-300 hover:text-white hover:bg-[#333]"}`,children:[n("span",{className:"font-medium",children:_.name}),d("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]},_.name))]}),s.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Saved Sizes"}),s.map(_=>d("div",{className:"flex items-center group hover:bg-[#333] transition-colors",children:[d("button",{onClick:()=>{o(_),l()},className:"flex-1 px-3 py-1.5 text-left text-xs text-gray-300 hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"font-medium",children:_.name}),d("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]}),n("button",{onClick:()=>i(_.name),className:"px-2 py-1.5 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all cursor-pointer",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M18 6L6 18M6 6l12 12"})})})]},_.name))]}),d("div",{className:"p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("input",{ref:b,type:"number",value:c,onChange:_=>u(_.target.value),onKeyDown:T,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Width"}),n("span",{className:"text-gray-500 text-xs flex-shrink-0",children:"×"}),n("input",{type:"number",value:p,onChange:_=>h(_.target.value),onKeyDown:T,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Height"})]}),d("div",{className:"flex gap-2",children:[n("button",{onClick:S,disabled:!w||!C,className:"flex-1 px-2 py-1.5 bg-[#007a99] text-white text-xs font-medium rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"Apply"}),y?d("div",{className:"flex gap-1",children:[n("input",{type:"text",value:m,onChange:_=>f(_.target.value),onKeyDown:T,placeholder:"Name",className:"w-20 px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white focus:outline-none focus:border-[#007a99]",autoFocus:!0}),n("button",{onClick:k,disabled:!m.trim()||!w,className:"px-2 py-1.5 bg-[#007a99] text-white text-xs rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"OK"})]}):n("button",{onClick:()=>g(!0),disabled:!w,className:"px-2 py-1.5 bg-[#333] text-gray-300 text-xs rounded hover:bg-[#444] transition-colors cursor-pointer disabled:text-gray-600 disabled:cursor-not-allowed",title:"Save as preset",children:"Save"})]})]})]})}function yi({width:e,height:t,onSave:r,onCancel:s}){const[o,a]=P(""),[i,l]=P(""),c=()=>{const u=o.trim();if(!u){l("Please enter a name");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("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:s,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"})})})]}),d("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"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:o,onChange:u=>{a(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&o.trim()&&c(),u.key==="Escape"&&s()},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})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:c,disabled:!o.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function No(e){const[t,r]=P([]),s=e?`codeyam-custom-sizes-${e}`:null;se(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const c=JSON.parse(l);Array.isArray(c)&&r(c)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const o=ce(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(c){console.error("[useCustomSizes] Failed to save custom sizes:",c)}},[s]),a=ce((l,c,u)=>{r(p=>{const h=p.findIndex(y=>y.name===l),m={name:l,width:c,height:u};let f;return h>=0?(f=[...p],f[h]=m):f=[...p,m],o(f),f})},[o]),i=ce(l=>{r(c=>{const u=c.filter(p=>p.name!==l);return o(u),u})},[o]);return{customSizes:t,addCustomSize:a,removeCustomSize:i}}function Gt(){return d("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
58
|
+
.loader {
|
|
59
|
+
width: 48px;
|
|
60
|
+
height: 48px;
|
|
61
|
+
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
62
|
+
border-radius: 50%;
|
|
63
|
+
display: inline-block;
|
|
64
|
+
position: relative;
|
|
65
|
+
box-sizing: border-box;
|
|
66
|
+
animation: rotation 1s linear infinite;
|
|
67
|
+
}
|
|
68
|
+
.loader::after {
|
|
69
|
+
content: '';
|
|
70
|
+
box-sizing: border-box;
|
|
71
|
+
position: absolute;
|
|
72
|
+
left: 50%;
|
|
73
|
+
top: 50%;
|
|
74
|
+
transform: translate(-50%, -50%);
|
|
75
|
+
width: 56px;
|
|
76
|
+
height: 56px;
|
|
77
|
+
border-radius: 50%;
|
|
78
|
+
border: 3px solid;
|
|
79
|
+
border-color: #005c75 transparent;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
@keyframes rotation {
|
|
83
|
+
0% {
|
|
84
|
+
transform: rotate(0deg);
|
|
85
|
+
}
|
|
86
|
+
100% {
|
|
87
|
+
transform: rotate(360deg);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
`})]})}const Kl=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],iy=80;function ar(){const[e,t]=P(0);return se(()=>{const r=setInterval(()=>{t(s=>(s+1)%Kl.length)},iy);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:Kl[e]})}async function ly({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw le("Invalid parameters",{status:400});const s=await In(t);if(!s)throw le("Entity not found",{status:404});const o=await fo(s),a=((l=o==null?void 0:o.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!a)throw le("Scenario not found",{status:404});const i=await Ye();return le({entity:s,scenario:a,analysis:o,projectSlug:i})}const ia=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1920,height:1080}],cy=nt(function(){const{entity:t,scenario:r,analysis:s,projectSlug:o}=lt(),a=zt(),[i]=lr(),[l,c]=P(null),[u,p]=P(1920),[h,m]=P({name:"Desktop",width:1920,height:1080}),[f,y]=P(!1),[g,x]=P(null),{customSizes:b,addCustomSize:v}=No(o),N=pe(()=>[...ia,...b],[b]),w=ye(null),[C,S]=P(1),k=ce(()=>{if(!w.current)return;const Y=32,B=w.current.clientWidth-Y,H=w.current.clientHeight-Y,ne=h.width,oe=h.height??900,Z=Math.min(1,B/ne,H/oe);S(Z)},[h.width,h.height]);se(()=>(k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)),[k]);const{interactiveServerUrl:T,isStarting:_,isLoading:$,showIframe:M,iframeKey:R,onIframeLoad:z}=Bn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),{lastLine:O}=Qt(o,_||$),U=()=>{a(`/entity/${t.sha}`)},W=(Y,B)=>{p(Y);const H=N.find(oe=>oe.width===Y&&oe.height===B);c(H||null),m({name:(H==null?void 0:H.name)||"Custom",width:Y,height:B})},J=Y=>{c(Y),p(Y.width),m({name:Y.name,width:Y.width,height:Y.height})},j=Y=>{v(Y,h.width,h.height??900),y(!1),m(B=>({...B,name:Y}))},D=((s==null?void 0:s.scenarios)||[]).filter(Y=>{var B;return!((B=Y.metadata)!=null&&B.sameAsDefault)}),A=D.findIndex(Y=>Y.id===(r==null?void 0:r.id)),L=A+1,E=D.length,F=A>0,I=A<D.length-1,K=()=>{if(F){const Y=D[A-1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen`);a(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen?from=${B}`)}},Q=()=>{if(I){const Y=D[A+1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen`);a(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen?from=${B}`)}},V=_||$||!M;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:uo,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:K,disabled:!F,className:`${F?"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"})})}),d("span",{className:"text-gray-400 text-sm",children:[L,"/",E]}),n("button",{onClick:Q,disabled:!I,className:`${I?"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"})})})]}),d("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)&&d("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:U,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"})})})]}),d("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:`${ia[ia.length-1].width}px`,width:"100%"},children:n(gi,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:J,devicePresets:N,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:h.name,onChange:Y=>{const B=N.find(H=>H.name===Y.target.value);B&&J(B)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(Y=>n("option",{value:Y.name,children:Y.name},Y.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:Y=>{const B=parseInt(Y.target.value,10);!isNaN(B)&&B>0&&W(B,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:w,className:"flex-1 flex items-center justify-center overflow-hidden p-4",style:{backgroundImage:`
|
|
91
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
92
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
93
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
94
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
95
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:T?d("div",{className:"relative bg-white",style:{width:`${h.width}px`,height:`${h.height??900}px`,transform:`scale(${C})`,transformOrigin:"center center"},children:[V&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Gt,{})}),d("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"}),O&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),O]})]})]})}),n("iframe",{src:T,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:z,style:{opacity:M?1:0}},R)]}):d("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(Gt,{})}),d("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"}),O&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),O]})]})]})}),f&&n(yi,{width:h.width,height:h.height??900,onSave:j,onCancel:()=>y(!1)})]})}),dy=Object.freeze(Object.defineProperty({__proto__:null,default:cy,loader:ly},Symbol.toStringTag,{value:"Module"})),tr={sound:"soft-double-tap",systemNotification:!0},uy=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],pu="codeyam-editor-notifications";function py(){try{const e=localStorage.getItem(pu);if(!e)return tr;const t=JSON.parse(e);return typeof t=="string"?t==="true"?tr:{...tr,sound:"off",systemNotification:!1}:{...tr,...t}}catch{return tr}}function hy(e){localStorage.setItem(pu,JSON.stringify(e))}function hu(e){var t;if(e!=="off")try{const r=new AudioContext,s={"soft-double-tap":o=>{[0,.12].forEach(a=>{const i=o.createOscillator(),l=o.createGain();i.connect(l),l.connect(o.destination),i.type="sine",i.frequency.value=392,l.gain.setValueAtTime(.25,o.currentTime+a),l.gain.exponentialRampToValueAtTime(.01,o.currentTime+a+.1),i.start(o.currentTime+a),i.stop(o.currentTime+a+.1)})},"gentle-chime":o=>{const a=o.createOscillator(),i=o.createGain();a.connect(i),i.connect(o.destination),a.type="sine",a.frequency.setValueAtTime(523,o.currentTime),a.frequency.setValueAtTime(659,o.currentTime+.15),i.gain.setValueAtTime(.3,o.currentTime),i.gain.exponentialRampToValueAtTime(.01,o.currentTime+.4),a.start(),a.stop(o.currentTime+.4)},"warm-ding":o=>{const a=o.createOscillator(),i=o.createGain();a.connect(i),i.connect(o.destination),a.type="sine",a.frequency.value=330,i.gain.setValueAtTime(.35,o.currentTime),i.gain.exponentialRampToValueAtTime(.01,o.currentTime+.6),a.start(),a.stop(o.currentTime+.6)},"mellow-two-tone":o=>{const a=o.createOscillator(),i=o.createGain();a.connect(i),i.connect(o.destination),a.type="sine",a.frequency.setValueAtTime(294,o.currentTime),a.frequency.setValueAtTime(440,o.currentTime+.18),i.gain.setValueAtTime(.3,o.currentTime),i.gain.exponentialRampToValueAtTime(.01,o.currentTime+.5),a.start(),a.stop(o.currentTime+.5)},"triangle-bell":o=>{const a=o.createOscillator(),i=o.createGain();a.connect(i),i.connect(o.destination),a.type="triangle",a.frequency.value=523,i.gain.setValueAtTime(.4,o.currentTime),i.gain.exponentialRampToValueAtTime(.01,o.currentTime+.8),a.start(),a.stop(o.currentTime+.8)}};(t=s[e])==null||t.call(s,r)}catch{}}function mu({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:o,notificationSettings:a,onChangeNotificationSettings:i}){const[l,c]=P(null),[u,p]=P(!1),h=ye(null),m=ye(null);se(()=>{if(!r)return;const b=new EventSource("/api/dev-mode-events");return b.onmessage=v=>{try{const N=JSON.parse(v.data);N.type==="file-synced"&&(c(N.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{b.close(),m.current&&clearTimeout(m.current)}},[r]),se(()=>{if(!u)return;function b(v){h.current&&!h.current.contains(v.target)&&p(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]);let f;s?f="error":t?f="starting":e?f="running":f="stopped";const y={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},g={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"},x=a&&(a.sound!=="off"||a.systemNotification);return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${y[f]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:g[f]})]}),(f==="stopped"||f==="error")&&o&&n("button",{onClick:o,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&d(ve,{children:[d("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&a&&d("div",{className:"relative",ref:h,children:[n("button",{onClick:()=>p(!u),className:`text-[11px] rounded transition-colors cursor-pointer ${x?"text-cygreen hover:text-cygreen/80":"text-gray-500 hover:text-gray-300"}`,children:x?"Notifications On":"Notifications Off"}),u&&d("div",{className:"absolute bottom-full right-0 mb-2 w-56 bg-[#2d2d2d] border border-[#4d4d4d] rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",children:[d("div",{children:[n("div",{className:"text-[11px] text-gray-400 mb-1.5",children:"Notification sound"}),n("div",{className:"flex flex-col gap-0.5",children:uy.map(b=>n("button",{onClick:()=>{i({...a,sound:b.id}),b.id!=="off"&&hu(b.id)},className:`text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors ${a.sound===b.id?"bg-[#444] text-white":"text-gray-300 hover:bg-[#3a3a3a]"}`,children:b.label},b.id))})]}),d("div",{className:"border-t border-[#4d4d4d] pt-2",children:[d("label",{className:"flex items-center gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:a.systemNotification,onChange:b=>{const v=b.target.checked;i({...a,systemNotification:v}),v&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n("span",{className:"text-[11px] text-gray-300",children:"System notification"})]}),n("div",{className:"text-[10px] text-gray-500 mt-1 ml-5",children:"Shows when tab is not visible"})]})]})]})]})}async function my(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),o=new s;return o.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),o.dispose(),Gl(e).then(a=>{a||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(o),{type:"webgl",dispose:()=>o.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await Gl(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function Gl(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}class fy{constructor(t,r){vt(this,"deferred",!1);vt(this,"userActiveSinceLastOutput",!1);vt(this,"actions");vt(this,"env");this.actions=t,this.env=r}reportUserActivity(){this.userActiveSinceLastOutput=!0}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){return this.deferred=!1,r&&this.env.hasBrowserFocus()&&this.userActiveSinceLastOutput?(this.userActiveSinceLastOutput=!1,"suppressed"):this.notify(t)}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){this.deferred=!1}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";return r&&this.actions.playSound(t.sound),!this.env.hasBrowserFocus()&&(t!=null&&t.systemNotification)&&this.env.hasNotificationPermission()&&this.actions.showSystemNotification(),r?"played":"played-no-sound"}}class gy{constructor(t){vt(this,"_isIdle",!1);vt(this,"_isBuilding",!1);vt(this,"callbacks");this.callbacks=t}get isIdle(){return this._isIdle}get isBuilding(){return this._isBuilding}handleClaudeIdle(t,r,s){console.log("[TerminalIdleHandler] claude-idle, building: %s → false",this._isBuilding),t==null||t.onIdle(r,s),this._isIdle=!0,this._isBuilding=!1,this.callbacks.onIdleChange(!0),this.callbacks.onBuildingChange(!1)}handleClaudeActive(t){console.log("[TerminalIdleHandler] claude-active, building: %s → true",this._isBuilding),this._isIdle=!1,this._isBuilding=!0,this.callbacks.onIdleChange(!1),this.callbacks.onBuildingChange(!0),t==null||t.onActive(),t==null||t.resetActivityFlag(),this.callbacks.onCloseNotification()}handleOutput(t){this.callbacks.onIdleChange(!1),t==null||t.resetActivityFlag()}reset(){this._isBuilding&&(console.log("[TerminalIdleHandler] reset, was building: true"),this._isBuilding=!1,this.callbacks.onBuildingChange(!1))}}const yy=`
|
|
96
|
+
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
97
|
+
.xterm.focus, .xterm:focus { outline: none; }
|
|
98
|
+
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
99
|
+
.xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
|
|
100
|
+
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
101
|
+
.xterm .composition-view.active { display: block; }
|
|
102
|
+
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
103
|
+
.xterm .xterm-screen { position: relative; }
|
|
104
|
+
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
105
|
+
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
106
|
+
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
107
|
+
.xterm.enable-mouse-events { cursor: default; }
|
|
108
|
+
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
109
|
+
.xterm.column-select.focus { cursor: crosshair; }
|
|
110
|
+
.xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
111
|
+
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
112
|
+
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
113
|
+
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
114
|
+
.xterm-dim { opacity: 1 !important; }
|
|
115
|
+
.xterm-underline-1 { text-decoration: underline; }
|
|
116
|
+
.xterm-underline-2 { text-decoration: double underline; }
|
|
117
|
+
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
118
|
+
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
119
|
+
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
120
|
+
.xterm-overline { text-decoration: overline; }
|
|
121
|
+
.xterm-strikethrough { text-decoration: line-through; }
|
|
122
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
123
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
124
|
+
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
125
|
+
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
126
|
+
`;function xy(){let e=document.getElementById("xterm-css");e||(e=document.createElement("style"),e.id="xterm-css",document.head.appendChild(e)),e.textContent=yy}const fu=Oh(function({entityName:t,entityType:r,entitySha:s,entityFilePath:o,scenarioName:a,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:u,onShowResults:p,onHideResults:h,onSetViewport:m,editorMode:f,onIdleChange:y,onBuildingChange:g,notificationSettings:x,buildTabActive:b,claudeStartMode:v,claudeSessionId:N,onFeatureComplete:w,onDataMutationForwarded:C,resultsOpen:S,editorStepLabel:k},T){const _=ye(null),$=ye(null),M=ye(null),R=ye(null),z=ye(null),O=ye(!1),U=ye(0),W=ye(!1),J=ye(y);J.current=y;const j=ye(g);j.current=g;const D=ye(x);D.current=x;const A=ye(b);A.current=b;const L=ye(S);L.current=S;const E=ye(null),F=ye(!1),I=ye(null);I.current||(I.current=new fy({playSound:B=>hu(B),showSystemNotification:()=>{E.current&&E.current.close();const B=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});B.onclick=()=>{window.focus(),B.close()},E.current=B}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"}));const K=ye(null);K.current||(K.current=new gy({onIdleChange:B=>{var H;F.current=B,(H=J.current)==null||H.call(J,B)},onCloseNotification:()=>{E.current&&(E.current.close(),E.current=null)},onBuildingChange:B=>{var H;(H=j.current)==null||H.call(j,B)}}));function Q(){E.current&&(E.current.close(),E.current=null)}function V(){var B,H;F.current&&(F.current=!1,Q(),(B=J.current)==null||B.call(J,!1),(H=I.current)==null||H.onUserEngagement())}se(()=>{function B(){var Z;document.hasFocus()&&A.current&&V(),A.current&&document.hasFocus()&&((Z=I.current)==null||Z.reportUserActivity())}function H(){!document.hidden&&A.current&&V()}function ne(){var Z;document.hasFocus()&&A.current&&V(),A.current&&document.hasFocus()&&((Z=I.current)==null||Z.reportUserActivity())}function oe(){var Z;A.current&&V(),A.current&&((Z=I.current)==null||Z.reportUserActivity())}return window.addEventListener("focus",oe),document.addEventListener("visibilitychange",H),document.addEventListener("mousemove",B),document.addEventListener("mousedown",ne),document.addEventListener("keydown",B),()=>{window.removeEventListener("focus",oe),document.removeEventListener("visibilitychange",H),document.removeEventListener("mousemove",B),document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",B)}},[]),se(()=>{var B;b&&F.current&&document.hasFocus()&&V(),(B=I.current)==null||B.onBuildTabChange(!!b,D.current)},[b]);const Y=ce(()=>{var B;(B=M.current)==null||B.focus()},[]);return Lh(T,()=>({sendInput(B){const H=R.current;H&&H.readyState===WebSocket.OPEN&&(H.send(JSON.stringify({type:"input",data:B})),setTimeout(()=>{H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var B;(B=M.current)==null||B.focus()},scrollToBottom(){var H;const B=(H=_.current)==null?void 0:H.querySelector(".xterm-viewport");B&&(B.scrollTop=B.scrollHeight)}})),se(()=>{const B=_.current;if(!B)return;let H=!1;return xy(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([ne,oe,Z])=>{if(H)return;const re=new ne.Terminal({cursorBlink:!1,cursorInactiveStyle:"none",scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#1e1e1e",selectionBackground:"#264f78"},linkHandler:{activate(ie,he){try{const Te=new URL(he),xe=Te.searchParams.get("scenario");if(xe&&Te.pathname.startsWith("/editor")){const Oe=new BroadcastChannel("codeyam-editor");Oe.postMessage({type:"switch-scenario",scenarioId:xe}),Oe.close();return}}catch{}window.open(he,"_blank")}}}),ue=new oe.FitAddon;re.loadAddon(ue),re.loadAddon(new Z.WebLinksAddon),re.open(B),re.attachCustomKeyEventHandler(ie=>{if(L.current&&(ie.key==="ArrowLeft"||ie.key==="ArrowRight")&&!ie.ctrlKey&&!ie.altKey&&!ie.metaKey&&ie.type==="keydown"){const he=ie.key==="ArrowLeft"?"\x1B[D":"\x1B[C",Te=R.current;return Te&&Te.readyState===WebSocket.OPEN&&Te.send(JSON.stringify({type:"input",data:he})),!1}return!0}),re.write("\x1B[?25l");let we=null;my(re,(ie,he,Te)=>{console.warn(`[Terminal] Renderer fallback: ${ie} → ${he}`,Te)}).then(ie=>{if(H){ie.dispose();return}console.log(`[Terminal] Using ${ie.type} renderer`),we=ie.dispose}),requestAnimationFrame(()=>{try{ue.fit()}catch{}}),M.current=re,re.focus(),setTimeout(()=>re.focus(),100),setTimeout(()=>re.focus(),500);const je=window.location.protocol==="https:"?"wss:":"ws:",be=window.location.host;function Ee(ie){const he=new URLSearchParams;return he.set("entityName",t),r&&he.set("entityType",r),s&&he.set("entitySha",s),o&&he.set("entityFilePath",o),a&&he.set("scenarioName",a),i&&he.set("scenarioDescription",i),l&&he.set("analysisId",l),c&&he.set("projectSlug",c),f&&he.set("editorMode","true"),ie&&he.set("reconnectId",ie),v&&he.set("claudeStartMode",v),N&&he.set("claudeSessionId",N),k&&he.set("editorStepLabel",k),`${je}//${be}/ws/terminal?${he.toString()}`}function X(ie){const he=Ee(ie),Te=new WebSocket(he);R.current=Te,Te.onopen=()=>{U.current=0,W.current=!1,Te.send(JSON.stringify({type:"resize",cols:re.cols,rows:re.rows}))},Te.onmessage=xe=>{var Oe,Je,bt;try{const Ge=JSON.parse(xe.data);if(Ge.type==="session-id"){z.current=Ge.sessionId;return}if(Ge.type==="refresh-preview"){u==null||u(Ge.path,Ge.scenarioId);return}if(Ge.type==="show-results"){p==null||p();return}if(Ge.type==="hide-results"){h==null||h();return}if(Ge.type==="feature-complete"){w==null||w();return}if(Ge.type==="data-mutation-forwarded"){C==null||C();return}if(Ge.type==="set-viewport"){m==null||m({name:Ge.name,width:Ge.width,height:Ge.height});return}if(Ge.type==="claude-idle"){(Oe=K.current)==null||Oe.handleClaudeIdle(I.current,D.current,A.current??!1);return}if(Ge.type==="claude-active"){(Je=K.current)==null||Je.handleClaudeActive(I.current);return}Ge.type==="output"&&(re.write(Ge.data),(bt=K.current)==null||bt.handleOutput(I.current))}catch{re.write(xe.data)}},Te.onclose=()=>{var Oe,Je;if(console.log("[Terminal] WS closed, intentional=%s",O.current),O.current){re.write(`\r
|
|
127
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
128
|
+
`),(Oe=K.current)==null||Oe.reset();return}const xe=U.current;if(xe<5&&z.current){const bt=1e3*Math.pow(2,Math.min(xe,3));U.current=xe+1,re.write(`\r
|
|
129
|
+
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
130
|
+
`),setTimeout(()=>{O.current||X(z.current)},bt)}else W.current?(re.write(`\r
|
|
131
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
132
|
+
`),(Je=K.current)==null||Je.reset()):(W.current=!0,re.write(`\r
|
|
133
|
+
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
134
|
+
`),z.current=null,U.current=0,X())},Te.onerror=()=>{}}X(),re.onData(ie=>{const he=R.current;he&&he.readyState===WebSocket.OPEN&&he.send(JSON.stringify({type:"input",data:ie})),V()});let fe=null;const ae=new ResizeObserver(()=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{let ie;try{ie=ue.proposeDimensions()}catch{return}if(!ie||ie.cols===re.cols&&ie.rows===re.rows)return;const he=B.querySelector(".xterm-viewport");let Te,xe=!0;he&&(Te=he.scrollTop,xe=he.scrollTop+he.clientHeight>=he.scrollHeight-10),ue.fit(),he&&Te!==void 0&&(xe?he.scrollTop=he.scrollHeight:he.scrollTop=Te);const Oe=R.current;Oe&&Oe.readyState===WebSocket.OPEN&&Oe.send(JSON.stringify({type:"resize",cols:re.cols,rows:re.rows}))},150)});ae.observe(B),$.current=()=>{var ie;fe&&clearTimeout(fe),ae.disconnect(),O.current=!0,(ie=R.current)==null||ie.close(),R.current=null,we==null||we(),re.dispose(),M.current=null}}),()=>{var ne;H=!0,(ne=$.current)==null||ne.call($),$.current=null}},[]),n("div",{ref:_,onClick:Y,className:"w-full h-full relative overflow-hidden",style:{padding:"4px 0 0 8px"}})});function ut({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:o}){const[a,i]=P("loading"),[l,c]=P(!1),u=ye(null),p=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),c(!0)},m=()=>{i("error"),c(!1)};return se(()=>{i("loading"),c(!1);const f=u.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[p]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:o,children:[n("img",{ref:u,src:p,alt:r,onLoad:h,onError:m,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),a==="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"})})}),a==="error"&&d("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:o,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function by({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const o=zt();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(a=>{var c,u;const i=a.id===t,l=(u=(c=a.metadata)==null?void 0:c.screenshotPaths)==null?void 0:u[0];return d("button",{onClick:()=>{o(`/entity/${r}/scenarios/${a.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(ut,{screenshotPath:l,cacheBuster:s,alt:a.name,className:"w-full h-full object-cover object-top"})}),d("div",{className:"p-2.5 min-w-0 flex-1",children:[d("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),a.name]}),a.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:a.description})]})]},a.id)})})}function $t(e){var l;if(!e.startsWith("app/")&&!e.startsWith("("))return"/";const r=e.replace(/^app\//,"").split("/"),s=r.pop(),o=((l=s.match(/\.(tsx?|jsx?|js)$/))==null?void 0:l[0])||"",a=s.slice(0,-o.length);let i;return a==="page"||a==="index"?i=r:i=[...r,a],i=i.filter(c=>!c.startsWith("(")),i.length===0?"/":"/"+i.join("/")}function Ut(e){return e==="/"?"Home":e.replace(/^\//,"").split("/").map(r=>r.startsWith("[")?r:r.charAt(0).toUpperCase()+r.slice(1)).join(" / ")}function gu(e,t){if(!e)return null;const r=e.split("?")[0].replace(/\/+$/,"")||"/",s=t.map(l=>({filePath:l,pattern:$t(l)})),o=r==="/"?[]:r.replace(/^\//,"").split("/");let a=null,i=-1;for(const l of s){const c=l.pattern==="/"?[]:l.pattern.replace(/^\//,"").split("/");if(c.length!==o.length)continue;let u=!0,p=0;for(let h=0;h<c.length;h++){const m=c[h],f=o[h];if(!(m.startsWith("[")&&m.endsWith("]")))if(m===f)p++;else{u=!1;break}}u&&p>i&&(i=p,a=l.filePath)}return a}function yu(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function Ct(e){if(!e||e==="/")return"Home";const t=e.split("?")[0].replace(/^\//,"");if(!t)return"Home";const r=t.split("/")[0].replace(/\.[^.]+$/,"");return r.charAt(0).toUpperCase()+r.slice(1)}function So(e){return e?e.includes("/isolated-components")||e.includes("/codeyam-isolate"):!1}function tn(e){return e.componentName?e.componentName:e.pageFilePath?Ut($t(e.pageFilePath)):Ct(e.url)}function xu(e,t,r){var a;const s=[],o=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.pageFilePath)l=i.displayName||(i.pageFilePath.startsWith("app/")?Ut($t(i.pageFilePath)):Ct(i.url)),c=i.pageFilePath;else if(!i.componentName&&i.url!==void 0){const u=Ct(i.url);t[u]&&(l=u,c=t[u])}if(l&&c&&!o.has(l)){o.add(l);const u=r.find(p=>p.name===l)||(c?r.find(p=>p.filePath===c):void 0);s.push({name:l,filePath:c,importedBy:(a=u==null?void 0:u.metadata)==null?void 0:a.importedBy})}}return s}function vy(e,t){const r=[],s=new Set(t);for(const o of e)s.has(o.name)||(s.add(o.name),r.push({name:o.name,filePath:o.filePath}));return r}function wy(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function Ny(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const o=tn(r);return!!t[o]}const s=r.name.indexOf(" - ");if(s!==-1){const o=r.name.slice(0,s);return!!t[o]}return!!t.Home})}function Sy(e){const t=new Set,r=new Map;for(const o of e)t.add(o.name),o.filePath&&r.set(o.filePath,o.name);const s=new Map;for(const o of e){const a=o.importedBy;if(!a||typeof a!="object")continue;const i=new Set;for(const l of Object.keys(a))for(const c of Object.keys(a[l]))if(t.has(c))i.add(c);else{const u=r.get(l);u&&u!==o.name?i.add(u):i.add(c)}i.size>0&&s.set(o.name,i)}return s}function Cy(e,t){const r=new Map;for(const s of t){const o=e.get(s.filePath);o&&r.set(s.name,o)}return r}const ky=20;function bu(e,t,r=ky){const s={};if(t.length===0||e.size===0)return s;const o=new Map;for(const u of t)o.set(u.name,u);const a=Sy(t),i=Cy(e,t);for(const[u,p]of i)s[u]={status:p};const l=new Map;for(const[u]of i)l.set(u,new Set([u]));const c=[];for(const[u]of i)c.push({name:u,depth:0});for(;c.length>0;){const{name:u,depth:p}=c.shift();if(p>=r)continue;const h=l.get(u)||new Set,m=a.get(u);if(m)for(const f of m){if(!o.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of h)y.has(x)||(y.add(x),g=!0);g&&c.push({name:f,depth:p+1})}}for(const[u,p]of l){if(i.has(u))continue;const h=[];for(const m of p){const f=o.get(m),y=i.get(m);f&&y&&h.push({name:m,filePath:f.filePath,changeType:y})}h.sort((m,f)=>m.name.localeCompare(f.name)),s[u]={status:"impacted",impactedBy:h.length>0?h:void 0}}return s}function Co(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e;for(const s of["components","entries","functions","glossary"]){const o=t[s];if(Array.isArray(o))return o}for(const s of Object.values(t))if(Array.isArray(s))return s;const r=Object.entries(t);if(r.length>0&&r.every(([,s])=>s&&typeof s=="object"&&!Array.isArray(s)))return r.map(([s,o])=>({...o,filePath:s}))}return[]}function Ey(e){return Co(e).filter(r=>r.testFile&&r.returnType!=="JSX.Element"&&r.returnType!=="React.ReactNode").map(r=>({name:r.name,filePath:r.filePath,description:r.description||"",testFile:r.testFile,feature:r.feature}))}function ql(e,t){var r,s,o,a,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((o=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&o[0])&&!((a=e.metadata)!=null&&a.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function _y(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var h;const s=r.analyses[0],o=s.scenarios||[],a=!((h=s.status)!=null&&h.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=o.filter(m=>ql(m,l)),u=o.filter(m=>!ql(m,l)),p=t.find(m=>m.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:a,scenarioCount:o.length,scenarios:c.map(m=>{var f,y;return{id:m.id,name:m.name,description:m.description||"",screenshotPath:((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:u.map(m=>m.name),testFile:p==null?void 0:p.testFile}})}function jy(e,t){var s;const r={};for(const o of e){const i=(((s=o.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[o.name]=i)}return r}function Py(e,t,r){const s={...e},o=new Map;for(const a of r)a.filePath&&o.set(a.filePath,a.name);for(const[a,i]of Object.entries(t)){if(s[a])continue;const l=o.get(i);l&&s[l]&&(s[a]=s[l])}return s}function Tt(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Dt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function vu(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Xr(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function xi(e,t){return!!(e.created_at&&e.created_at>=t||e.updated_at&&e.updated_at>=t)}const Ay=["defaultScreenSize","screenSizes","projectTitle","projectDescription","appFormats"];function F_(e){try{const t=JSON.parse(de.readFileSync(e,"utf8")),r={};for(const s of Ay)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function Ty(e){const t=ee.join(e,".codeyam","editor-step.json");try{de.unlinkSync(t)}catch{}}function bi(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function My(e){var t,r;try{const s=ee.join(e,".codeyam","config.json"),o=JSON.parse(de.readFileSync(s,"utf8"));if(o.screenSizes&&typeof o.screenSizes=="object")for(const a of Object.values(o.screenSizes)){const i=a;if(i.default&&i.width&&i.height)return{width:i.width,height:i.height}}if((t=o.defaultScreenSize)!=null&&t.width&&((r=o.defaultScreenSize)!=null&&r.height))return{width:o.defaultScreenSize.width,height:o.defaultScreenSize.height}}catch{}return null}function vi(e){try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(de.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function $y(e){var t,r;return{width:e.bodyWidth||((t=e.projectDefault)==null?void 0:t.width)||1280,height:e.bodyHeight||((r=e.projectDefault)==null?void 0:r.height)||720}}function ko(e){let t=null;if(e.dimension){const o=vi(e.codeyamRoot)[e.dimension];o!=null&&o.width&&(o!=null&&o.height)&&(t={width:o.width,height:o.height})}const r=t||My(e.codeyamRoot);return $y({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function Fy(e,t){const r=t.dimensions?JSON.stringify(t.dimensions):null,s=t.screenshotPaths?JSON.stringify(t.screenshotPaths):null,o=await e.selectFrom("editor_scenarios").selectAll().where("name","=",t.name).where("project_id","=",t.projectId).orderBy("created_at","desc").execute();if(o.length>0){const c=o[0].id,u={description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};t.dimensions!==void 0&&(u.dimensions=r,u.screenshot_paths=s),t.pageFilePath!==void 0&&(u.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(u.entity_sha=t.entitySha),t.displayName!==void 0&&(u.display_name=t.displayName),await e.updateTable("editor_scenarios").set(u).where("id","=",c).execute();const p=o.slice(1).map(h=>h.id);return p.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",p).execute(),{scenarioId:c,isNew:!1,cleanedUpIds:p}}const a=globalThis.crypto.randomUUID(),i={id:a,project_id:t.projectId,name:t.name,description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight};return t.dimensions!==void 0&&(i.dimensions=r,i.screenshot_paths=s),t.pageFilePath!==void 0&&(i.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(i.entity_sha=t.entitySha),t.displayName!==void 0&&(i.display_name=t.displayName),await e.insertInto("editor_scenarios").values(i).execute(),{scenarioId:a,isNew:!0,cleanedUpIds:[]}}function Ry(e,t){const r=ee.join(e,".codeyam","editor-scenarios"),s=ee.join(r,"screenshots");for(const o of t){for(const a of[`${o}.json`,`${o}.seed.json`,ee.join("screenshots",`${o}.png`)])try{de.unlinkSync(ee.join(r,a))}catch{}try{const a=de.readdirSync(s);for(const i of a)if(i.startsWith(`${o}--`)&&i.endsWith(".png"))try{de.unlinkSync(ee.join(s,i))}catch{}}catch{}}}function Dy(e){const{lookupFilePath:t,scenarioType:r,projectRoot:s}=e;if(r!=="application"&&r!=="user")return{valid:!0};if(!t)return{valid:!0};const o=ee.join(s,".codeyam","glossary.json");let a=[];try{const l=JSON.parse(de.readFileSync(o,"utf8"));a=Co(l)}catch{}if(!a.some(l=>l.filePath===t)){const l=a.length===0?` glossary.json is empty or could not be parsed. It must be a JSON array: [{"name": "...", "filePath": "${t}", ...}]`:` Found ${a.length} entries but none with filePath "${t}".`;return{valid:!1,error:`No glossary entry found for '${t}'.${l} Add this file to .codeyam/glossary.json before registering app scenarios.`}}return{valid:!0,needsAnalysis:!0}}function Iy(e){const{componentName:t,url:r}=e;return!t||!r?{valid:!0}:So(r)?{valid:!0}:{valid:!1,error:`Scenario has componentName "${t}" but URL "${r}" is not an isolation route. Component scenarios must use an isolation URL like /isolated-components/${t}?s=ScenarioName or /codeyam-isolate/${t}?s=ScenarioName. Either change the URL to an isolation route, or remove componentName to register as an application scenario.`}}const Oy=wu;async function wu(e,t){const r=new Map,s=new Map;for(const i of t)if(i.filePath){r.set(`${i.name}::${i.filePath}`,i);const l=s.get(i.filePath);(!l||!l.isDefaultExport||i.isDefaultExport)&&s.set(i.filePath,i)}const o=await e.selectFrom("editor_scenarios").selectAll().where(i=>i.or([i("component_path","is not",null),i("page_file_path","is not",null)])).execute();if(o.length===0)return{updated:0};let a=0;for(const i of o){const l=i,c=l.component_path||l.page_file_path;if(!c)continue;const u=l.component_name&&r.get(`${l.component_name}::${c}`)||s.get(c);if(!u||l.entity_sha===u.sha)continue;let p=null;l.component_name?p=l.component_name:l.page_file_path&&l.page_file_path.startsWith("app/")?p=Ut($t(l.page_file_path)):l.url&&(p=Ct(l.url)),await e.updateTable("editor_scenarios").set({entity_sha:u.sha,...p?{display_name:p}:{}}).where("id","=",l.id).execute(),a++}return{updated:a}}async function Ql(e,t,r){const s=ee.join(e,".codeyam","editor-scenarios"),o=i=>{const l=ee.join(s,`${i}.seed.json`);if(de.existsSync(l))try{return JSON.parse(de.readFileSync(l,"utf-8"))}catch{return null}const c=ee.join(s,`${i}.json`);if(de.existsSync(c))try{return JSON.parse(de.readFileSync(c,"utf-8")).seed||null}catch{return null}return null},a=o(r);if(a)return a;try{const i=await t.selectFrom("editor_scenarios").select("id").where("name","=",r).orderBy("created_at","desc").limit(1).executeTakeFirst();if(i)return o(i.id)}catch{}return null}function Ly(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:o,proxyUrl:a,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const u=o.find(p=>p.id===s);if(u!=null&&u.url){const p=a||i;return p?u.url.startsWith("/")?`${p}${u.url}`:u.url:null}}const c=a||i;if(!c)return null;if(l&&s){const u=o.find(h=>h.id===s),p=u?Dt(u.name):"Default";return`${c}/__codeyam__/${l}/${p}`}return c}function Nu(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function zy(e,t){return e?e!==t:!1}function Ss(e){if(e.length!==0)return e.find(t=>t.url==="/")||e.find(t=>t.type==="application")||e[0]}function la(e,t,r){if(!e.viewportWidth||!e.viewportHeight)return r??null;const s=t.find(o=>o.width===e.viewportWidth&&o.height===e.viewportHeight);return{name:(s==null?void 0:s.name)||"Custom",width:e.viewportWidth,height:e.viewportHeight}}function Zl(e,t){const r=t.width,s=t.height??900,o=e.width,a=e.height;return r<=o&&s<=a?1:Math.min(o/r,a/s)}async function By({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw le("Invalid parameters",{status:400});const s=await In(t);if(!s)throw le("Entity not found",{status:404});const o=await fo(s),a=((l=o==null?void 0:o.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!a)throw le("Scenario not found",{status:404});const i=await Ye();return le({entity:s,scenario:a,analysis:o,projectSlug:i})}const ca=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Yy=nt(function(){const{entity:t,scenario:r,analysis:s,projectSlug:o}=lt(),a=zt(),i=ye(null),l=ye(null),[c,u]=P(null),[p,h]=P(1440),[m,f]=P({name:"Desktop",width:1440,height:900}),[y,g]=P(!1),[x,b]=P(null),[v,N]=P("chat"),[w,C]=P(0),[S,k]=P(null),T=ce(re=>{k(re||null),C(ue=>ue+1)},[]),{customSizes:_,addCustomSize:$}=No(o),M=pe(()=>[...ca,..._],[_]),{interactiveServerUrl:R,isStarting:z,isLoading:O,showIframe:U,iframeKey:W,onIframeLoad:J}=Bn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0,refreshTrigger:w}),j=pe(()=>Nu(R,S),[R,S]),{lastLine:D}=Qt(o,z||O),A=()=>{a(`/entity/${t.sha}`)},L=(re,ue)=>{h(re);const we=M.find(be=>be.width===re&&be.height===ue);u(we||null),f({name:(we==null?void 0:we.name)||"Custom",width:re,height:ue})},E=re=>{u(re),h(re.width),f({name:re.name,width:re.width,height:re.height})},F=re=>{$(re,m.width,m.height??900),g(!1),f(ue=>({...ue,name:re}))},I=()=>{var ue;N("chat"),(ue=l.current)==null||ue.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},K=((s==null?void 0:s.scenarios)||[]).filter(re=>{var ue;return!((ue=re.metadata)!=null&&ue.sameAsDefault)}),Q=K.findIndex(re=>re.id===(r==null?void 0:r.id)),V=Q+1,Y=K.length,B=Q>0,H=Q<K.length-1,ne=()=>{if(B){const re=K[Q-1];a(`/entity/${t.sha}/scenarios/${re.id}/dev`)}},oe=()=>{if(H){const re=K[Q+1];a(`/entity/${t.sha}/scenarios/${re.id}/dev`)}},Z=z||O||!U;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:uo,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:ne,disabled:!B,className:`${B?"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"})})}),d("span",{className:"text-gray-400 text-sm",children:[V,"/",Y]}),n("button",{onClick:oe,disabled:!H,className:`${H?"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"})})})]}),d("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)&&d("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("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:A,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",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"})})})]}),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[d("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:`${ca[ca.length-1].width}px`,width:"100%"},children:n(gi,{currentViewportWidth:p,currentPresetName:m.name,onDevicePresetClick:E,devicePresets:M,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("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:(x==null?void 0:x.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"})})]}),d("select",{value:m.name,onChange:re=>{const ue=M.find(we=>we.name===re.target.value);ue&&E(ue)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[M.map(re=>n("option",{value:re.name,children:re.name},re.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:re=>{const ue=parseInt(re.target.value,10);!isNaN(ue)&&ue>0&&L(ue,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:"x"}),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:`
|
|
135
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
136
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
137
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
138
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
139
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:R?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[Z&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Gt,{})}),d("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:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),D&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),D]})]})]})}),n("iframe",{ref:i,src:j||R,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:J,style:{opacity:U?1:0}},W)]}):d("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(Gt,{})}),d("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 Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),D&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),D]})]})]})})]}),d("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[d("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-0",children:[d("button",{onClick:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",v==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),d("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",v==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),v==="chat"&&n("button",{onClick:I,disabled:!R,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:v==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(fu,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:o,onRefreshPreview:T})}),v==="scenarios"&&n(by,{scenarios:K,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(mu,{serverUrl:R,isStarting:z,projectSlug:o}),y&&n(yi,{width:m.width,height:m.height??900,onSave:F,onCancel:()=>g(!1)})]})}),Uy=Object.freeze(Object.defineProperty({__proto__:null,default:Yy,loader:By},Symbol.toStringTag,{value:"Module"})),Su=3e4,Wy="seed-session.json";function Jy(e){const t={};try{const r=q.readFileSync(e,"utf-8");for(const s of r.split(`
|
|
140
|
+
`)){const o=s.trim();if(!o||o.startsWith("#"))continue;const a=o.indexOf("=");if(a===-1)continue;const i=o.slice(0,a).trim();let l=o.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i&&(t[i]=l)}}catch{}return t}function Cu(e){const t=[".env",".env.local",".env.development",".env.development.local"];let r={};for(const s of t){const o=Jy(G.join(e,s));r={...r,...o}}return r}function ku(e){const t={};try{const r=G.join(e,".codeyam","config.json"),s=JSON.parse(q.readFileSync(r,"utf-8"));for(const o of s.environmentVariables||[]){const a=o.key||o.name;a&&o.value!==void 0&&(t[a]=o.value)}}catch{}return t}function Hy(e){const t=G.join(e,".codeyam","tmp",Wy);try{if(!q.existsSync(t))return{};const r=q.readFileSync(t,"utf-8"),s=JSON.parse(r);q.unlinkSync(t);const o={};return s.cookies&&Array.isArray(s.cookies)&&(o.sessionCookies=s.cookies),s.externalApis&&typeof s.externalApis=="object"&&(o.externalApis=s.externalApis),o}catch{return{}}}function wi(e,t,r){const s=Su,o=G.basename(G.dirname(e))===".codeyam"?G.dirname(G.dirname(e)):G.dirname(e);return new Promise(a=>{const i=Date.now(),l=e.endsWith(".ts");let c,u;if(l){const b=Ky(o);b?(c=b,u=[e,t]):(c="npx",u=["tsx",e,t])}else c=e,u=[t];const p=Cu(o),h=ku(o),m=kt(c,u,{cwd:o,env:{...process.env,...p,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;if(g)a({success:!1,output:f,error:`Seed adapter timeout after ${s}ms`,durationMs:v});else if(b===0){const N=Hy(o);a({success:!0,output:f,durationMs:v,sessionCookies:N.sessionCookies,externalApis:N.externalApis})}else a({success:!1,output:f,error:y||`Seed adapter exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),a({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function Vy(e,t,r){const s=Su,o=G.basename(G.dirname(e))===".codeyam"?G.dirname(G.dirname(e)):G.dirname(e);return new Promise(a=>{const i=Date.now(),l=e.endsWith(".ts"),c=l?"npx":e,u=l?["tsx",e,"--export",t]:["--export",t],p=Cu(o),h=ku(o),m=kt(c,u,{cwd:o,env:{...process.env,...p,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;a(g?{success:!1,output:f,error:`Seed adapter export timeout after ${s}ms`,durationMs:v}:b===0?{success:!0,output:f,durationMs:v}:{success:!1,output:f,error:y||`Seed adapter export exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),a({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function Wr(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=G.join(e,".codeyam",r);try{return q.accessSync(s),s}catch{}}return null}function Ky(e){const t=[G.join(e,"node_modules",".bin","tsx"),G.join(e,"..","node_modules",".bin","tsx")];for(const r of t)try{return q.accessSync(r,q.constants.X_OK),r}catch{}return null}function Xl(e,t){const r={};for(const[s,o]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(o));for(const[s,o]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(o));return r}let En=null;async function Eo(e){const{scenarioId:t,projectRoot:r}=e,s=ee.join(r,".codeyam"),o=ee.join(s,"editor-scenarios");let a=e.scenarioSlug||null;if(!a)try{const m=ee.join(o,`${t}.json`);de.existsSync(m)?a=JSON.parse(de.readFileSync(m,"utf-8")).name||t:a=t}catch{a=t}let i=e.scenarioType||null;if(!i)try{const m=ee.join(o,`${t}.json`);de.existsSync(m)&&(i=JSON.parse(de.readFileSync(m,"utf-8")).type||null)}catch{}const l=ee.join(s,"active-scenario.json");de.mkdirSync(s,{recursive:!0}),de.writeFileSync(l,JSON.stringify({scenarioSlug:a,scenarioName:e.scenarioName||a,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let c=null,u,p;const h=i==="application"||i==="user";if(h)if(En&&En.scenarioId===t)c=await En.promise;else{const m=Wr(r),f=ee.join(o,`${t}.seed.json`);if(m&&de.existsSync(f)){const y=wi(m,f).then(g=>({success:g.success,error:g.error,sessionCookies:g.sessionCookies,externalApis:g.externalApis}));En={scenarioId:t,promise:y};try{const g=await y;c={success:g.success,error:g.error},u=g.sessionCookies,p=g.externalApis}finally{En&&En.scenarioId===t&&(En=null)}if(c!=null&&c.success){const g=u&&u.length>0,x=p&&Object.keys(p).length>0;if(g||x)try{const b=ee.join(o,`${t}.json`),v=JSON.parse(de.readFileSync(b,"utf-8"));g&&(v.sessionCookies=u),x&&(v.externalApis={...v.externalApis,...p}),de.writeFileSync(b,JSON.stringify(v,null,2))}catch{}}}else m||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:a,scenarioId:t,type:i,seeded:h,...c?{seedResult:c}:{},...u&&u.length>0?{sessionCookies:u}:{}}}function Gy(e){return dr.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function qy(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function Qy(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,o)=>(t.push(o),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function Zy(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function Xy(){let e=[],t={},r=null,s=null,o=!1,a=null;function i(u){const p=[],h=u.routes;if(h&&typeof h=="object")for(const[m,f]of Object.entries(h)){const{method:y,pathPattern:g}=qy(m),{regex:x,paramNames:b}=Qy(g),v=typeof f=="object"&&f!==null?f:{body:f};p.push({method:y,pathPattern:g,pathRegex:x,paramNames:b,response:{body:v.body,status:typeof v.status=="number"?v.status:200}})}return p}function l(u){const p=u.state;if(p&&typeof p=="object"){o=!0,t={};for(const[h,m]of Object.entries(p))t[h]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[];r=JSON.stringify(p)}else o=!1,t={},r=null}return{loadScenario(u){const p=Gy(u);s&&p===s||(s=p,a=u,e=i(u),l(u))},matchRequest(u,p,h){if(!a&&e.length===0&&!o)return null;const m=Object.keys(t);if(o){const y=Zy(p,m);if(y&&u==="GET"&&y===p)return{body:t[y],status:200};if(y){const g=c(u,p);if(u==="POST"&&y===p&&g){const x=t[y],b=typeof h=="object"&&h!==null?{...h}:{};if(!("id"in b)){const v=x.reduce((N,w)=>{const C=typeof w.id=="number"?w.id:0;return Math.max(N,C)},0);b.id=v+1}return x.push(b),{body:b,status:g.response.status}}if(u==="DELETE"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(N=>String(N.id)===String(x));return v===-1?{body:{error:"Not found"},status:404}:(b.splice(v,1),{body:null,status:g.response.status})}if(u==="PUT"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(w=>String(w.id)===String(x));if(v===-1)return{body:{error:"Not found"},status:404};const N=typeof h=="object"&&h!==null?{...h}:b[v];return b[v]=N,{body:N,status:g.response.status}}}}const f=c(u,p);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(a&&u==="GET"){const y=p.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in a&&g!=="routes"&&g!=="state")return{body:a[g],status:200}}}return null},resetState(){if(r){const u=JSON.parse(r);t={};for(const[p,h]of Object.entries(u))t[p]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[]}},getState(){return{...t}}};function c(u,p){for(const h of e)if(h.method!==null&&h.method===u&&h.paramNames.length===0&&h.pathRegex.exec(p))return{response:h.response};if(u==="GET"){for(const h of e)if(h.method===null&&h.paramNames.length===0&&h.pathRegex.exec(p))return{response:h.response}}for(const h of e)if(h.paramNames.length>0){if((h.method??"GET")!==u)continue;const f=h.pathRegex.exec(p);if(f){const y={};for(let g=0;g<h.paramNames.length;g++)y[h.paramNames[g]]=f[g+1];return{response:h.response,params:y}}}return null}}function ex(e){var o,a;const t=ee.join(e,"package.json");if(!de.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(de.readFileSync(t,"utf8"));if(de.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":de.existsSync(ee.join(e,"yarn.lock"))?r="yarn":de.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((o=i.scripts)!=null&&o.dev))if((a=i.scripts)!=null&&a.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function tx(e,t){const r=t.toString(),s={PORT:r},o=ee.join(e,".codeyam","config.json");if(de.existsSync(o))try{const c=(JSON.parse(de.readFileSync(o,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:u,args:p,env:h}=c.startCommand,m=(p||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(h)for(const[f,y]of Object.entries(h))typeof y=="string"&&y.includes("$PORT")?s[f]=y.replace(/\$PORT/g,r):typeof y=="string"&&(s[f]=y);return{command:u,args:m,env:s}}}catch{}const a=ex(e);return"error"in a?a:{command:a.command,args:a.args,env:s}}function Eu(e){return{proxyPort:e+1,devServerPort:e+2}}const nx=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/waiting on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function rx(e){for(const t of nx){const r=e.match(t);if(r){const s=r[1]||r[0];return sx(s).trim()}}return null}function sx(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ni(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function ox(e,t={}){const{intervalMs:r=2e3,maxAttempts:s=15}=t,o=`http://localhost:${e}`;for(let a=0;a<s;a++){try{const i=await fetch(o,{method:"HEAD",signal:AbortSignal.timeout(2e3)});if(i.ok||i.status===304)return o}catch{}a<s-1&&await new Promise(i=>setTimeout(i,r))}return null}function ax(e){const{exitCode:t,uptime:r,retryCount:s,wasRunning:o}=e,a=r<1e4;return t!==0&&t!==null&&a&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:o===!1?{action:"error"}:{action:"stopped"}}class ix extends Gr{emitDataMutationForwarded(t,r){this.emit("event",{type:"data-mutation-forwarded",method:t,pathname:r,timestamp:Date.now()})}}const Fa="__codeyam_mock_state_event_emitter__";if(!globalThis[Fa]){const e=new ix;e.setMaxListeners(20),globalThis[Fa]=e}const lx=globalThis[Fa];function cx(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function dx(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(o=>{const a=new $d.Socket;a.setTimeout(1e3),a.once("connect",()=>{a.destroy(),o(!0)}),a.once("error",()=>{a.destroy(),o(!1)}),a.once("timeout",()=>{a.destroy(),o(!1)}),a.connect(e,r)}))return r}catch{}return null}const _u="__codeyam_editor_proxy__",ju="__codeyam_preview_health__";function Pu(){return globalThis[ju]??null}function Au(e){globalThis[ju]=e}function ec(){return Pu()}function Tu(){Au(null)}const ux=`<script data-codeyam-health>
|
|
141
|
+
(function() {
|
|
142
|
+
var errors = [];
|
|
143
|
+
var reported = false;
|
|
144
|
+
function report(type, msg, stack) {
|
|
145
|
+
errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
|
|
146
|
+
if (!reported) {
|
|
147
|
+
reported = true;
|
|
148
|
+
setTimeout(function() { flush(); }, 500);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function flush() {
|
|
152
|
+
fetch('/__codeyam__/preview-health', {
|
|
153
|
+
method: 'POST',
|
|
154
|
+
headers: { 'Content-Type': 'application/json' },
|
|
155
|
+
body: JSON.stringify({ errors: errors, url: location.href })
|
|
156
|
+
}).catch(function(){});
|
|
157
|
+
reported = false;
|
|
158
|
+
errors = [];
|
|
159
|
+
}
|
|
160
|
+
window.addEventListener('error', function(e) {
|
|
161
|
+
report('error', e.message, e.error && e.error.stack);
|
|
162
|
+
});
|
|
163
|
+
window.addEventListener('unhandledrejection', function(e) {
|
|
164
|
+
report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
|
|
165
|
+
});
|
|
166
|
+
var origError = console.error;
|
|
167
|
+
console.error = function() {
|
|
168
|
+
report('console.error', Array.prototype.join.call(arguments, ' '));
|
|
169
|
+
origError.apply(console, arguments);
|
|
170
|
+
};
|
|
171
|
+
window.addEventListener('load', function() {
|
|
172
|
+
setTimeout(function() {
|
|
173
|
+
var hasContent = document.body && document.body.innerText.trim().length > 0;
|
|
174
|
+
fetch('/__codeyam__/preview-health', {
|
|
175
|
+
method: 'POST',
|
|
176
|
+
headers: { 'Content-Type': 'application/json' },
|
|
177
|
+
body: JSON.stringify({
|
|
178
|
+
loaded: true,
|
|
179
|
+
hasContent: hasContent,
|
|
180
|
+
url: location.href,
|
|
181
|
+
errorCount: errors.length
|
|
182
|
+
})
|
|
183
|
+
}).catch(function(){});
|
|
184
|
+
}, 1000);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// Network-idle detection: notify the parent editor when all initial
|
|
188
|
+
// fetch requests have completed, so it can show the preview after
|
|
189
|
+
// client-side data (API calls) has arrived — not just when the DOM loads.
|
|
190
|
+
var inflight = 0;
|
|
191
|
+
var settled = false;
|
|
192
|
+
var settleTimer = null;
|
|
193
|
+
var origFetch = window.fetch;
|
|
194
|
+
window.fetch = function() {
|
|
195
|
+
if (!settled) inflight++;
|
|
196
|
+
return origFetch.apply(this, arguments).then(function(resp) {
|
|
197
|
+
if (!settled) { inflight--; checkSettle(); }
|
|
198
|
+
return resp;
|
|
199
|
+
}, function(err) {
|
|
200
|
+
if (!settled) { inflight--; checkSettle(); }
|
|
201
|
+
throw err;
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
function checkSettle() {
|
|
205
|
+
if (inflight <= 0 && !settled) {
|
|
206
|
+
clearTimeout(settleTimer);
|
|
207
|
+
// Small delay to allow React to re-render with the fetched data
|
|
208
|
+
settleTimer = setTimeout(function() {
|
|
209
|
+
if (inflight <= 0) {
|
|
210
|
+
settled = true;
|
|
211
|
+
try {
|
|
212
|
+
window.parent.postMessage({ type: 'codeyam-preview-ready' }, '*');
|
|
213
|
+
} catch(e) {}
|
|
214
|
+
}
|
|
215
|
+
}, 100);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// Fallback: if no fetches happen (static page), settle after load
|
|
219
|
+
window.addEventListener('load', function() {
|
|
220
|
+
setTimeout(function() { checkSettle(); }, 200);
|
|
221
|
+
});
|
|
222
|
+
})();
|
|
223
|
+
<\/script>`,px=500;let Kt={data:null,timestamp:0},jt,mn,_o=null,jo=null,Po=null,Ra=null;const tc=10*1024*1024;function Ao(){return globalThis[_u]??null}function Mu(e){globalThis[_u]=e}function $u(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=Xy()),globalThis[e]}function Fu(){const e=Ao();return e?`http://localhost:${e.port}`:null}function hx(){const e=Date.now();if(Kt.data!==null&&e-Kt.timestamp<px)return Kt.data;const t=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!de.existsSync(r))return Kt={data:null,timestamp:e},null;const s=JSON.parse(de.readFileSync(r,"utf-8")),o=s.scenarioId;if(!o)return Po=s.prototypeId||null,Kt={data:null,timestamp:e},null;const a=ee.join(t,".codeyam","editor-scenarios",`${o}.json`);if(!de.existsSync(a))return console.log(`[editorProxy] Scenario data file not found: ${a}`),Kt={data:null,timestamp:e},null;const i=JSON.parse(de.readFileSync(a,"utf-8"));jt=i.session||null,mn=i.sessionCookies||void 0,_o=i.localStorage||null,jo=o;const l=s.type||i.type||null;Ra=l;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Kt={data:c,timestamp:e},$u().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Kt={data:null,timestamp:e},null}}function mx(e){return new Promise(t=>{const r=[];let s=0;e.on("data",o=>{s+=o.length,s>tc?(t(null),e.resume()):r.push(o)}),e.on("end",()=>{s>tc||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function Si(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function nc(e,t,r,s){const o=new URL(r),a=Si(o.hostname),i={...e.headers,host:`${o.hostname}:${o.port}`};delete i["accept-encoding"],Du(i),s&&(i["content-length"]=String(s.length));const l={hostname:a,port:o.port,path:e.url,method:e.method,headers:i},c=ni.request(l,u=>{const p=u.statusCode||200;p>=300&&p<400&&console.log(`[editorProxy] Target redirect ${p} for ${e.method} ${e.url} → ${u.headers.location}`),p>=400&&console.warn(`[editorProxy] Target returned ${p} for ${e.method} ${e.url}`);const h={...u.headers};if(Ru(h),(u.headers["content-type"]||"").includes("text/html")){Tu();const f=[];u.on("data",y=>f.push(y)),u.on("end",()=>{const y=Buffer.concat(f).toString("utf-8"),g=Iu(_o,jo||"",Po),x=Ou(y,g);delete h["content-length"],delete h["content-encoding"],h["cache-control"]="no-store, must-revalidate",t.writeHead(p,h),t.end(x)});return}t.writeHead(p,h),u.pipe(t,{end:!0})});c.on("error",u=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${u.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function fx(e,t,r){const s=new URL(r),o=Si(s.hostname),{"accept-encoding":a,...i}=e.headers,l={...i,host:`${s.hostname}:${s.port}`};Du(l);const c={hostname:o,port:s.port,path:e.url,method:e.method,headers:l},u=ni.request(c,p=>{const h=p.statusCode||200;h>=300&&h<400&&console.log(`[editorProxy] Target redirect ${h} for ${e.method} ${e.url} → ${p.headers.location}`),h>=400&&console.warn(`[editorProxy] Target returned ${h} for ${e.method} ${e.url}`);const m={...p.headers};if(Ru(m),(p.headers["content-type"]||"").includes("text/html")){Tu();const y=[];p.on("data",g=>y.push(g)),p.on("end",()=>{const g=Buffer.concat(y).toString("utf-8"),x=Iu(_o,jo||"",Po),b=Ou(g,x);delete m["content-length"],delete m["content-encoding"],m["cache-control"]="no-store, must-revalidate",t.writeHead(h,m),t.end(b)});return}t.writeHead(h,m),p.pipe(t,{end:!0})});u.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(u,{end:!0})}function Ru(e){const t=[];if(jt!==void 0&&(jt!=null&&jt.cookieValue?t.push(`session-token=${jt.cookieValue}; Path=/; SameSite=Lax`):t.push("session-token=; Path=/; Max-Age=0")),mn&&mn.length>0)for(const s of mn){const o=s.path||"/",a=s.sameSite||"Lax";t.push(`${s.name}=${s.value}; Path=${o}; SameSite=${a}`)}if(t.length===0)return;const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],...t]:e["set-cookie"]=t}function gx(){const e=[];if(jt!=null&&jt.cookieValue&&e.push({name:"session-token",value:jt.cookieValue}),mn&&mn.length>0)for(const t of mn)e.push({name:t.name,value:t.value});return e.length>0?e:null}function Du(e){const t=gx();if(!t)return;const r=typeof e.cookie=="string"?e.cookie:"",s=r?r.split(";").map(i=>i.trim()):[],o=new Map;for(const i of s){const l=i.indexOf("=");l!==-1&&o.set(i.slice(0,l),i.slice(l+1))}for(const{name:i,value:l}of t)o.set(i,l);const a=[];for(const[i,l]of o)a.push(`${i}=${l}`);a.length>0&&(e.cookie=a.join("; "))}function yx(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function Iu(e,t,r){if(!e||typeof e!="object"){const c=t?`clear:${t}`:"";return r?`<script data-codeyam-ls>
|
|
224
|
+
(function() {
|
|
225
|
+
if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(r)}) return;
|
|
226
|
+
localStorage.clear();
|
|
227
|
+
localStorage.setItem('__codeyam_proto__', ${JSON.stringify(r)});
|
|
228
|
+
})();
|
|
229
|
+
<\/script>`:t?`<script data-codeyam-ls>
|
|
230
|
+
(function() {
|
|
231
|
+
if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(c)}) return;
|
|
232
|
+
var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
|
|
233
|
+
for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
|
|
234
|
+
localStorage.removeItem('__codeyam_ls_keys__');
|
|
235
|
+
localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(c)});
|
|
236
|
+
})();
|
|
237
|
+
<\/script>`:""}const s=Object.entries(e),o=s.map(([c])=>c),a=s.map(([c,u])=>{const p=typeof u=="string"?u:JSON.stringify(u);return`localStorage.setItem(${JSON.stringify(c)}, ${JSON.stringify(p)});`}).join(`
|
|
238
|
+
`),i=yx(JSON.stringify(e)),l=`${t}:${i}`;return`<script data-codeyam-ls>
|
|
239
|
+
(function() {
|
|
240
|
+
if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(l)}) return;
|
|
241
|
+
var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
|
|
242
|
+
for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
|
|
243
|
+
${a}
|
|
244
|
+
localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(o))});
|
|
245
|
+
localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(l)});
|
|
246
|
+
})();
|
|
247
|
+
<\/script>`+xx()}function xx(){return`<script data-codeyam-ls-watcher>
|
|
248
|
+
(function() {
|
|
249
|
+
if (window.__codeyam_ls_watcher_installed__) return;
|
|
250
|
+
window.__codeyam_ls_watcher_installed__ = true;
|
|
251
|
+
|
|
252
|
+
var origSet = localStorage.setItem.bind(localStorage);
|
|
253
|
+
var origRemove = localStorage.removeItem.bind(localStorage);
|
|
254
|
+
var origClear = localStorage.clear.bind(localStorage);
|
|
255
|
+
window.__codeyam_orig_setItem__ = origSet;
|
|
256
|
+
window.__codeyam_orig_removeItem__ = origRemove;
|
|
257
|
+
window.__codeyam_orig_clear__ = origClear;
|
|
258
|
+
|
|
259
|
+
function isInternal(key) {
|
|
260
|
+
return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
localStorage.setItem = function(key, value) {
|
|
264
|
+
origSet(key, value);
|
|
265
|
+
if (!isInternal(key) && window.parent !== window) {
|
|
266
|
+
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
localStorage.removeItem = function(key) {
|
|
271
|
+
origRemove(key);
|
|
272
|
+
if (!isInternal(key) && window.parent !== window) {
|
|
273
|
+
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
localStorage.clear = function() {
|
|
278
|
+
origClear();
|
|
279
|
+
if (window.parent !== window) {
|
|
280
|
+
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
window.addEventListener('message', function(event) {
|
|
285
|
+
if (event.data && event.data.type === 'codeyam-get-localstorage') {
|
|
286
|
+
var data = {};
|
|
287
|
+
for (var i = 0; i < localStorage.length; i++) {
|
|
288
|
+
var k = localStorage.key(i);
|
|
289
|
+
if (k && !isInternal(k)) {
|
|
290
|
+
data[k] = localStorage.getItem(k);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
})();
|
|
297
|
+
<\/script>`}function Ou(e,t){const r=(t||"")+ux;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function bx(e,t){const r=[];e.on("data",s=>r.push(s)),e.on("end",()=>{try{const s=JSON.parse(Buffer.concat(r).toString("utf-8")),o=Pu()||{errors:[],loaded:!1,hasContent:!1,url:"",lastUpdated:0};s.errors&&Array.isArray(s.errors)&&(o.errors=o.errors.concat(s.errors)),s.loaded!==void 0&&(o.loaded=s.loaded),s.hasContent!==void 0&&(o.hasContent=s.hasContent),s.url&&(o.url=s.url),o.lastUpdated=Date.now(),Au(o)}catch{}t.writeHead(204),t.end()})}function vx(e,t,r,s){const o=new URL(s),a=Si(o.hostname),i=parseInt(o.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a}:${i}`);const l=$d.connect(i,a,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
298
|
+
`,u=Object.entries(e.headers).filter(([,p])=>p!=null).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(`\r
|
|
299
|
+
`);l.write(c+u+`\r
|
|
300
|
+
\r
|
|
301
|
+
`),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function wx(e,t){const r=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{de.mkdirSync(ee.dirname(s),{recursive:!0}),de.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(o){console.warn("[editorProxy] Failed to write proxy-config.json:",o)}}function Nx(){const e=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{de.existsSync(t)&&de.unlinkSync(t)}catch{}}async function Da(e){const t=Ao();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await Lu();let r=cx(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const c=parseInt(l.port||"80",10),u=await dx(c);u&&(l.hostname=u,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${u} for port ${c}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const o=$u(),a=ni.createServer((l,c)=>{(async()=>{const p=new URL(l.url||"/",`http://localhost:${s}`).pathname,h=l.method||"GET";if(h==="OPTIONS"){c.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),c.end();return}if(h==="POST"&&p==="/__codeyam__/preview-health"){bx(l,c);return}if(hx(),h==="POST"||h==="PUT"||h==="DELETE"||h==="PATCH"){const y=await mx(l);if(y===null){nc(l,c,r,null);return}let g;if(y.length>0)try{g=JSON.parse(y.toString("utf-8"))}catch{}const x=o.matchRequest(h,p,g);if(x){console.log(`[editorProxy] Intercepted ${h} ${p} → mock response (status ${x.status})`),c.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(x.body!=null?JSON.stringify(x.body):"");return}(Ra==="application"||Ra==="user")&&p.startsWith("/api/")&&lx.emitDataMutationForwarded(h,p),nc(l,c,r,y);return}const f=o.matchRequest(h,p);if(f){console.log(`[editorProxy] Intercepted ${h} ${p} → mock response (status ${f.status})`),c.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(f.body!=null?JSON.stringify(f.body):"");return}fx(l,c,r)})()});a.on("upgrade",(l,c,u)=>{vx(l,c,u,r)});const i=10;for(let l=0;l<i;l++){const c=s+l;try{await new Promise((h,m)=>{a.once("error",m),a.listen(c,"0.0.0.0",()=>{a.removeListener("error",m),h()})});const u=a.address();return s=typeof u=="object"&&u!==null?u.port:c,Mu({server:a,port:s,targetUrl:r}),wx(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(u){if((u==null?void 0:u.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",u),null}}return null}async function Lu(){const e=Ao();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),Nx(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Mu(null),setTimeout(t,2e3)})}function On(){Kt={data:null,timestamp:0},jt=void 0,mn=void 0,_o=null,jo=null,Po=null}async function rc(){const e=Ao();if(!e)return console.warn("[editorProxy] Cannot verify — proxy is not running"),!1;try{const t=await fetch(`http://127.0.0.1:${e.port}/`,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return t.status===502?(console.warn("[editorProxy] Verification failed — proxy returned 502 (target unreachable)"),!1):(console.log(`[editorProxy] Verification passed — proxy forwarding to ${e.targetUrl} (status ${t.status})`),!0)}catch{return console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${e.port}`),!1}}async function Ci(){const e=Fu();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:s}=Eu(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const o=await Da({port:s,targetUrl:t.url});if(o){const a=`http://localhost:${o.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}async function Sx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,scenarioName:s,scenarioSlug:o}=t;if(!r||typeof r!="string")return Response.json({error:"scenarioId is required"},{status:400});const a=Ce()||process.cwd(),i=await Eo({scenarioId:r,scenarioName:s,scenarioSlug:o,projectRoot:a});return On(),Response.json({success:i.success,seeded:i.seeded,seedResult:i.seedResult})}catch(t){const r=t instanceof Error?t.message:String(t);return Response.json({error:r},{status:500})}}const Cx=Object.freeze(Object.defineProperty({__proto__:null,action:Sx},Symbol.toStringTag,{value:"Module"}));async function kx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:o,viewportHeight:a}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=G.join(i,".codeyam","journal","screenshots");await Pe.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),u=G.join(l,`${c}.png`),p=G.dirname(new URL(import.meta.url).pathname);let h=p;for(let v=0;v<5;v++){const N=G.dirname(h);if(G.basename(N)==="webserver"||G.basename(h)==="webserver"){h=G.basename(h)==="webserver"?h:N;break}h=N}const m=[G.join(h,"scripts","journalCapture.ts"),G.join(h,"app","lib","journalCapture.ts"),G.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),G.resolve(p,"..","lib","journalCapture.ts")];let f="";for(const v of m)try{await Pe.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${m.join(", ")}`),f=m[0]);const y=ko({bodyWidth:o,bodyHeight:a,codeyamRoot:i}),g=JSON.stringify({url:r,outputPath:u,viewportWidth:y.width,viewportHeight:y.height}),x=await new Promise(v=>{const N=kt("npx",["tsx",f,g],{cwd:i,env:{...process.env}});let w="",C="";N.stdout.on("data",S=>{w+=S.toString()}),N.stderr.on("data",S=>{C+=S.toString()}),N.on("close",S=>{v(S===0?{success:!0,output:w}:{success:!1,output:w,error:C||`Process exited with code ${S}`})}),N.on("error",S=>{v({success:!1,output:"",error:S.message})})});if(!x.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:x.error}),{status:500,headers:{"Content-Type":"application/json"}});const b=`screenshots/${c}.png`;return new Response(JSON.stringify({success:!0,path:b}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ex=Object.freeze(Object.defineProperty({__proto__:null,action:kx},Symbol.toStringTag,{value:"Module"}));async function _x({request:e}){const t={"Content-Type":"application/json"};try{const r=Ce()||process.cwd(),s=await e.json(),{scenarioId:o,table:a,rowIndex:i,column:l,value:c}=s;if(!o||!a||i==null||!l)return new Response(JSON.stringify({success:!1,error:"Missing required fields"}),{headers:t,status:400});const u=G.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!q.existsSync(u))return new Response(JSON.stringify({success:!1,error:"Scenario file not found"}),{headers:t,status:404});const p=JSON.parse(q.readFileSync(u,"utf-8"));if(Array.isArray(p[a])&&i<p[a].length)return p[a][i][l]=c,q.writeFileSync(u,JSON.stringify(p,null,2)),new Response(JSON.stringify({success:!0}),{headers:t});if(p.seed&&typeof p.seed=="object"){const h=a.charAt(0).toLowerCase()+a.slice(1);for(const m of[a,h,`${h}s`])if(Array.isArray(p.seed[m])&&i<p.seed[m].length){p.seed[m][i][l]=c,q.writeFileSync(u,JSON.stringify(p,null,2));const f=u.replace(/\.json$/,".seed.json");if(q.existsSync(f))try{const y=JSON.parse(q.readFileSync(f,"utf-8"));Array.isArray(y[m])&&(y[m][i][l]=c,q.writeFileSync(f,JSON.stringify(y,null,2)))}catch{}return new Response(JSON.stringify({success:!0}),{headers:t})}}if(p.localStorage&&typeof p.localStorage=="object"){for(const[h,m]of Object.entries(p.localStorage))if(typeof m=="string")try{let f=JSON.parse(m);const y=!Array.isArray(f)&&typeof f=="object"&&f!==null;if(y&&(f=[f]),!Array.isArray(f))continue;const g=a.charAt(0).toLowerCase()+a.slice(1),x=()=>{f[i][l]=c;const b=y?f[0]:f;p.localStorage[h]=JSON.stringify(b),q.writeFileSync(u,JSON.stringify(p,null,2))};if((h===a||h===g||h===`${g}s`||h===`${a}s`)&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t});if(f.length>0&&l in f[0]&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t})}catch{}}return new Response(JSON.stringify({success:!1,error:"Table not found in scenario"}),{headers:t,status:404})}catch(r){return new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{headers:t,status:500})}}const jx=Object.freeze(Object.defineProperty({__proto__:null,action:_x},Symbol.toStringTag,{value:"Module"})),zu=Ga({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),ki=()=>{const e=ao(zu);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},To=({children:e})=>{const[t,r]=P({height:720,width:1200}),[s,o]=P(1),[a,i]=P(1200),l=ye(null),c=ce(({height:h,width:m})=>{r(f=>({height:h??f.height,width:m??f.width}))},[]),u=ce(h=>{o(h)},[]),p=ce(h=>{i(h)},[]);return n(zu.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:u,maxWidth:a,updateMaxWidth:p},children:e})},Px=typeof window<"u";function Ax(){const[e,t]=P(null);return se(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Tx=1200,Mx=720,sc=30,$x=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:o=900,onDataOverride:a,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const u=Ax(),[p,h]=P(!1),[m,f]=P(!1),[y,g]=P(Tx),[x,b]=P(Mx),[v,N]=P(null),[w,C]=P(null),{dimensions:S,updateDimensions:k,iframeRef:T,updateScale:_,updateMaxWidth:$}=ki(),M=pe(()=>Math.min(1,y/S.width),[y,S.width]),R=w!==null?w:M;se(()=>{p||(_(R),l==null||l(R))},[R,_,l,p]),se(()=>{$(y)},[y,$]);const z=ce(()=>{h(!0),C(M)},[M]),O=ce(()=>{h(!1),C(null)},[]),U=ce((A,L)=>{const E=w!==null?w:1,F=Math.round(L.size.width/E);k({width:F}),c==null||c(F,S.height)},[k,w,c,S.height]),W=ce(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);se(()=>{const A=L=>{if(L.data.type==="codeyam-resize"){if(t&&L.data.name!==t||S.height===L.data.height||L.data.height===0)return;k({height:L.data.height})}};return window.addEventListener("message",A),()=>{window.removeEventListener("message",A)}},[T,t,s,S,k]),se(()=>{m&&a&&a(T.current)},[m,a,T]),se(()=>{if(!t)return;const A=setInterval(()=>{var L,E;(E=(L=T==null?void 0:T.current)==null?void 0:L.contentWindow)==null||E.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(A)},[t,T]),se(()=>{const A=()=>{const L=document.getElementById("scenario-container");if(!L)return;const E=L.getBoundingClientRect(),F=L.clientWidth-sc*2,I=window.innerHeight-E.top-sc*2,K=Math.max(I,400),Q=window.innerHeight-E.top;g(F),b(K),N(Q)};return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]),se(()=>{k({width:s,height:o})},[s,o,k]);const J=pe(()=>S.width*R,[S.width,R]),j=pe(()=>{const A=S.height,L=A*R;return A&&A!==720&&A!==900&&L<x?L:x},[S.height,x,R]),D=ce(()=>{window.history.back()},[]);return!Px||!u?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..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[p&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
302
|
+
.react-resizable-handle-e {
|
|
303
|
+
display: flex !important;
|
|
304
|
+
align-items: center !important;
|
|
305
|
+
justify-content: center !important;
|
|
306
|
+
width: 6px !important;
|
|
307
|
+
height: 48px !important;
|
|
308
|
+
right: -8px !important;
|
|
309
|
+
top: 50% !important;
|
|
310
|
+
transform: translateY(-50%) !important;
|
|
311
|
+
cursor: ew-resize !important;
|
|
312
|
+
background: #d1d5db !important;
|
|
313
|
+
border-radius: 3px !important;
|
|
314
|
+
opacity: 0 !important;
|
|
315
|
+
transition: all 0.2s ease !important;
|
|
316
|
+
}
|
|
317
|
+
.react-resizable-handle-e:hover {
|
|
318
|
+
opacity: 0.8 !important;
|
|
319
|
+
background: #9ca3af !important;
|
|
320
|
+
}
|
|
321
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
322
|
+
opacity: 0.4 !important;
|
|
323
|
+
}
|
|
324
|
+
`}),n(u,{width:J,height:j,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:z,onResizeStop:O,onResize:U,children:n("div",{className:"overflow-auto",style:{width:`${J}px`,height:`${j}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${R})`,transformOrigin:"top left"},children:r?n("iframe",{ref:T,className:"w-full h-full rounded-lg",src:r,onLoad:W,sandbox:"allow-scripts allow-same-origin"}):d("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:D,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Fx({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:o,onSizeChange:a,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[u,p]=P(!1),[h,m]=P(String(r)),[f,y]=P(String(s)),[g,x]=P(!1),[b,v]=P(!1),N=ye(null);se(()=>{g||m(String(r))},[r,g]),se(()=>{b||y(String(s))},[s,b]),se(()=>{const R=z=>{N.current&&!N.current.contains(z.target)&&p(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[]);const w=pe(()=>{const R=e.find(O=>O.width===r&&O.height===s);if(R)return R.name;const z=t.find(O=>O.width===r&&O.height===s);return z?z.name:"Custom"},[e,t,r,s]),C=w==="Custom",S=R=>{a(R.width,R.height),p(!1)},k=R=>{const z=R.target.value;m(z);const O=parseInt(z,10);!isNaN(O)&&O>0&&a(O,s)},T=R=>{const z=R.target.value;y(z);const O=parseInt(z,10);!isNaN(O)&&O>0&&a(r,O)},_=()=>{x(!1);const R=parseInt(h,10);(isNaN(R)||R<=0)&&m(String(r))},$=()=>{v(!1);const R=parseInt(f,10);(isNaN(R)||R<=0)&&y(String(s))},M=R=>{(R.key==="Enter"||R.key==="Escape")&&R.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:N,children:[d("button",{onClick:()=>p(!u),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:w}),n("svg",{className:`w-4 h-4 transition-transform ${u?"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"})})]}),u&&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:d("div",{className:"py-1",children:[e.length>0&&d(ve,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(R=>d("button",{onClick:()=>S(R),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===R.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:R.name}),d("span",{className:"text-xs text-gray-500",children:[R.width," x ",R.height]})]},R.name))]}),t.length>0&&d(ve,{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((R,z)=>R.width-z.width).map(R=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===R.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>S(R),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:R.name}),d("span",{className:"text-xs text-gray-500",children:[R.width," x ",R.height]})]}),l&&n("button",{onClick:z=>{z.stopPropagation(),w===R.name&&e.length>0&&a(e[0].width,e[0].height),l(R.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"})})})]},R.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:k,onFocus:()=>x(!0),onBlur:_,onKeyDown:M,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),d("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:T,onFocus:()=>v(!0),onBlur:$,onKeyDown:M,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),o!==void 0&&o<1&&d("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),C&&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 da(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function Ia(e){return e&&(typeof e=="object"||Array.isArray(e))}function Rx(e){return Array.isArray(e)?e.length:void 0}function Dx(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,o)=>o.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((o,a)=>{const i=Ia(t[o]),l=Ia(t[a]);return i&&!l?1:!i&&l?-1:o.localeCompare(a)});if(typeof t=="object")return Object.keys(t).sort((o,a)=>o.localeCompare(a))}}function Ix({scenarioFormData:e,handleInputChange:t}){return d("div",{className:"p-3 flex flex-col gap-3",children:[d("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"})]}),d("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 Ox({path:e,namedPath:t,isArray:r,count:s,onClick:o}){const a=ce(()=>{o&&o(e)},[o,e]);return d("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:a,children:[d("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"})}),d("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),d("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 Bu=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Bu||{});const Lx=({name:e,value:t,options:r,onChange:s})=>{const o=ce(a=>{s({target:{name:e,value:a.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:o,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((a,i)=>n("option",{value:a.trim(),children:a.trim()},i))})},zx=({name:e,value:t,onChange:r})=>{const s=ce(o=>{const a=o.target.checked;r({target:{name:e,value:a}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
325
|
+
bg-gray-300 checked:bg-blue-600
|
|
326
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
327
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
328
|
+
checked:after:translate-x-4`})})};function Bx({dataType:e,path:t,value:r,onChange:s}){const o=pe(()=>t[t.length-1],[t]),a=pe(()=>t.join("-"),[t]),i=ce(c=>{s(t,c.target.value)},[s,t]),l=ce(c=>{s(t,c.target.value)},[s,t]);return d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:a,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?n(Lx,{name:a,value:r,options:e.split("|"),onChange:i}):e===Bu.BOOLEAN?n(zx,{name:a,value:r??!1,onChange:l}):n("input",{id:a,name:a,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-${a}`)]})}function Yx({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:o}){const[a,i]=P(!1),[l,c]=P(""),u=ce(async()=>{if(!o){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const m=e.scenarios.find(x=>x.name===ho),f=await o(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,b)=>{const v=Object.assign({},x);return g(x)&&g(b)&&Object.keys(b).forEach(N=>{g(b[N])?N in x?v[N]=y(x[N],b[N]):Object.assign(v,{[N]:b[N]}):Object.assign(v,{[N]:b[N]})}),v},g=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=y(y((m==null?void 0:m.metadata.data)||{},h.metadata.data),f.data||{}),s(h),i(!1),c("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,s,o]),p=ce(h=>{c(h.target.value)},[]);return d("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:p,value:l}),n("button",{type:"button",disabled:a,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 u(),children:a?d(ve,{children:[d("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 Ux({namedPath:e,path:t,last:r,onClick:s}){const o=ce(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function Wx({dataItem:e,onClick:t}){const r=ce(()=>t([]),[t]),s=pe(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return d("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&&d("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(s).map((o,a)=>d("div",{className:"flex items-center gap-1",children:[n(Ux,{namedPath:e.namedPath.slice(0,a+s+1),path:e.path.slice(0,a+s+1),last:a+s===e.namedPath.length-1,onClick:t}),a+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${o}-${a+s}`))]})}function oc({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:o,onAIResult:a,onGenerateData:i,saveFeedback:l}){const c=pe(()=>r.data,[r]),u=pe(()=>Dx(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Wx,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(Yx,{analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:i}),u==null?void 0:u.map((p,h)=>{var f;if(Ia(c[p])){let y=p;isNaN(Number(p))||(y=c[p].name??c[p].title??c[p].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(p)+1}`);const g=[...r.path,p],x=[...r.namedPath,y];return n(Ox,{path:g,namedPath:x,isArray:Array.isArray(c),count:Rx(c[p]),onClick:s},`data-${p}-${h}`)}if(p==="id")return null;const m=[...r.path,p];return n(Bx,{dataType:((f=r.structure)==null?void 0:f[p])??"string",path:m,value:c[p],onChange:o},`InputField-${m.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const p=document.getElementById("recapture-input");p&&(p.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 p=document.getElementById("recapture-input");p&&(p.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 ac({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:o=!1}){const[a,i]=P(r),l=[];return s&&l.push("border-t"),o&&l.push("border-b"),d("div",{className:`${l.join(" ")} border-gray-300`,children:[d("button",{type:"button",onClick:()=>i(!a),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 ${a?"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"})})]}),a&&n("div",{className:"px-4 py-3",children:t})]})}const Jx=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:o,onSave:a,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:u})=>{const p=ce((k,T)=>{const _=Object.assign({},k),$=M=>M&&typeof M=="object"&&!Array.isArray(M);return $(k)&&$(T)&&Object.keys(T).forEach(M=>{$(T[M])?M in k?_[M]=p(k[M],T[M]):Object.assign(_,{[M]:T[M]}):Object.assign(_,{[M]:T[M]})}),_},[]),[h,m]=P({name:e.name,description:e.description,data:p(t.metadata.data,e.metadata.data)}),[f,y]=P(null),g=pe(()=>({...h.data}),[h]),x=pe(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),b=pe(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((T,_)=>{if(_.includes(".")){const[$,M]=_.split(".");T[$]||(T[$]={}),T[$][M]=k[_]}else T[_]=k[_];return T},{})},[r]),v=ce(async k=>{k.preventDefault();const T=k.target.querySelector('input[name="recapture"]'),_=(T==null?void 0:T.value)==="true",$={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:_,dataToSave:$,rawFormData:h.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify($,null,2).substring(0,1e3));const M=s==null?void 0:s.scenarios.map(R=>!o&&R.name===e.name?{...R,name:h.name,description:h.description,metadata:{...R.metadata,data:$}}:R);o&&M.push({name:h.name,description:h.description,metadata:{data:$,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",M),a&&await a(M,{recapture:_}),i&&i(h.name)},[s,e.name,h,g,o,a,i]),N=ce(k=>{m(T=>({...T,[k.target.name]:k.target.value}))},[]),w=ce(k=>{y(T=>{if(!T)return null;for(const _ of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let $=_;for(const M of T.path)if($=da($,M),!$)break;$&&(T.data=$)}return{...T}}),m({name:k.name,description:k.description,data:k.metadata.data})},[]),C=ce((k,T)=>{m(_=>{for(const $ of[{"Function Arguments":_.data.argumentsData},{"Retrieved Data":_.data.mockData}]){let M=$;for(const R of k.slice(0,-1))if(M=da(M,R),!M)break;if(M){const R=M[k[k.length-1]];y(z=>z?(z.namedPath[z.namedPath.length-1]===R&&(z.namedPath[z.namedPath.length-1]=T.toString()),z.data[k[k.length-1]]=T,{...z}):null),M[k[k.length-1]]=T}}return{..._}})},[]),S=ce(k=>{var M,R,z;if(k.length===0){y(null);return}let T=x;const _=[];let $=b;for(const O of k){if(_.push(isNaN(parseInt(O))?O:((M=T[O])==null?void 0:M.name)??((R=T[O])==null?void 0:R.title)??((z=T[O])==null?void 0:z.id)??O),T=da(T,O),!T){console.log("Data not found",T,O),y(null);return}Array.isArray($)?$=$[0]:$=$[O]}y({path:k,namedPath:_,data:T,structure:$})},[x,b]);return se(()=>{const k=T=>{var _;T.data.type==="codeyam-log"&&((_=T.data.data)!=null&&_.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",T.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),se(()=>{var k;if((k=l==null?void 0:l.current)!=null&&k.contentWindow){const T={arguments:g.argumentsData??[],...g.mockData??{}},_={type:"codeyam-override-data",name:e.name,data:JSON.stringify(T)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:_.type,name:_.name,dataPreview:JSON.stringify(T).substring(0,200)+"...",fullData:T}),l.current.contentWindow.postMessage(_,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:k=>void v(k),children:f?n(oc,{analysis:s,scenarioName:h.name,dataItem:f,onClick:S,onChange:C,onAIResult:w,onGenerateData:c,saveFeedback:u}):d(ve,{children:[n(ac,{title:"Edit Name and Description",borderT:!0,children:n(Ix,{scenarioFormData:h,handleInputChange:N})}),e.metadata.data&&n(ac,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(oc,{analysis:s,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:S,onChange:C,onAIResult:w,onGenerateData:c,saveFeedback:u})})]})})};function Mo({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:o,showIframe:a,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:u,projectSlug:p,defaultWidth:h=1440,defaultHeight:m=900,retryCount:f=0}){const{lastLine:y}=Qt(p??null,s||o);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:a?1:0,background:"transparent"},children:n($x,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:m,onIframeLoad:l,onScaleChange:c,onDimensionChange:u},i)}),!a&&(s||o)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Gt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:d("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(Gt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),y]})]})]})})}const Hx=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Vx({params:e}){var c,u;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 s=await mo(t,!0),o=s&&s.length>0?s[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const a=(c=o.scenarios)==null?void 0:c.find(p=>p.id===r);if(!a)throw new Response("Scenario not found",{status:404});const i=(u=o.scenarios)==null?void 0:u.find(p=>p.name===ho),l=await Ye();return le({analysis:o,scenario:a,defaultScenario:i||a,entitySha:t,projectSlug:l})}function Kx(){var O,U,W;const e=lt(),t=e.analysis,r=e.scenario,s=e.defaultScenario,o=e.entitySha,a=e.projectSlug,i=zt(),{iframeRef:l}=ki(),[c,u]=P(!1),[p,h]=P(null),[m,f]=P(null),[y,g]=P(!1),[x,b]=P(!1),[v,N]=P(null),{interactiveServerUrl:w,isStarting:C,isLoading:S,showIframe:k,iframeKey:T,onIframeLoad:_}=Bn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),$=ce(async(J,j)=>{u(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",j),console.log("[EditScenario] Scenarios to save:",J);try{const D={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 A=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)}),L=await A.json();if(console.log("[EditScenario] API response:",L),!A.ok||!L.success)throw new Error(L.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),j!=null&&j.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),h("Changes saved. Capturing screenshot...");const E={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",E);const F=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});console.log("[EditScenario] Capture response status:",F.status);const I=await F.json();if(console.log("[EditScenario] Capture response body:",I),!F.ok||!I.success)throw console.error("[EditScenario] Capture failed:",I),new Error(I.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",I),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(j!=null&&j.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const E=new FormData;E.append("analysisId",t.id||""),E.append("scenarioId",r.id||"");const F=await fetch("/api/recapture-scenario",{method:"POST",body:E}),I=await F.json();if(!F.ok||!I.success)throw new Error(I.error||"Failed to trigger recapture");console.log("Recapture queued:",I),f(I.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(D){console.error("Error saving scenarios:",D),h(`Error: ${D instanceof Error?D.message:String(D)}`)}finally{u(!1)}},[t,r.id,w]),M=ce(J=>{},[]),R=ce(async(J,j)=>{var L;const D=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:J,existingScenarios:t.scenarios,scenariosDataStructure:(L=t.metadata)==null?void 0:L.scenariosDataStructure,editingMockName:r.name,editingMockData:j==null?void 0:j.data})}),A=await D.json();if(!D.ok||!A.success)throw new Error(A.error||"Failed to generate scenario data");return A.data},[t,r.name]),z=ce(async()=>{var J;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const j=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)||[]})}),D=await j.json();if(!j.ok||!D.success)throw new Error(D.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(j){console.error("[EditScenario] Error deleting scenario:",j),N(j instanceof Error?j.message:"Failed to delete scenario"),b(!1)}finally{g(!1)}},[r.id,(O=r.metadata)==null?void 0:O.screenshotPaths,o,i]);return d("div",{className:"h-screen bg-gray-50 flex flex-col",children:[d("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:d(ke,{to:`/entity/${o}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(U=t.entity)==null?void 0:U.name]})}),d("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})]}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[d("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Jx,{currentScenario:r,defaultScenario:s,dataStructure:((W=t.metadata)==null?void 0:W.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:$,onNavigate:M,iframeRef:l,onGenerateData:R,saveFeedback:{isSaving:c,message:p,isError:(p==null?void 0:p.startsWith("Error"))??!1}}),p==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(ke,{to:`/entity/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),d("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?d("div",{className:"space-y-3",children:[d("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void z(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>b(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),v&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:v})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Mo,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:C,isLoading:S,showIframe:k,iframeKey:T,onIframeLoad:_,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const Gx=nt(function(){return n(To,{children:n(Kx,{})})}),qx=Object.freeze(Object.defineProperty({__proto__:null,default:Gx,loader:Vx,meta:Hx},Symbol.toStringTag,{value:"Module"})),Qx=["/api/health","/__codeyam__/preview-health"];function Yu(e){const t=[];for(const r of e.split(`
|
|
329
|
+
`))if(r.includes("[JournalCapture] HTTP error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] API response error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] Page console.error:"))t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,""));else if(r.includes("[JournalCapture] Network failed:")){if(Qx.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}function Zx(e){for(const t of e.split(`
|
|
330
|
+
`))if(t.includes("[JournalCapture] Visible text: "))return t.replace(/.*\[JournalCapture\] Visible text: /,"");return null}async function Uu(e,t,r,s){const o=G.join(e,".codeyam","editor-scenarios","client-errors.json");let a={};try{const i=await Pe.readFile(o,"utf8");a=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(a))i!==t&&l.scenarioName===r&&delete a[i];a[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await Pe.mkdir(G.dirname(o),{recursive:!0}),await Pe.writeFile(o,JSON.stringify(a,null,2),"utf8")}async function Wu(e){const t=G.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Pe.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function Ei(e){let r=G.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const o=G.dirname(r);if(G.basename(o)==="webserver"||G.basename(r)==="webserver")return G.basename(r)==="webserver"?r:o;r=o}return r}async function _i(e,t){const r=[G.join(e,"scripts","journalCapture.ts"),G.join(e,"app","lib","journalCapture.ts"),G.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await Pe.access(s),s}catch{}return r[0]}function ji(e,t,r){return new Promise(s=>{const o=e.endsWith(".ts"),l=kt(o?"npx":e,o?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",u="";l.stdout.on("data",p=>{c+=p.toString()}),l.stderr.on("data",p=>{u+=p.toString()}),l.on("close",p=>{s(p===0?{success:!0,output:c}:{success:!1,output:c,error:u||`Process exited with code ${p}`})}),l.on("error",p=>{s({success:!1,output:"",error:p.message})})})}function Xx(e){const t=G.join(e,".codeyam","editor-scenarios");let r;try{r=q.readdirSync(t)}catch{return[]}const s=[];for(const o of r){if(!o.endsWith(".json")||o.endsWith(".seed.json")||o==="client-errors.json")continue;const a=G.join(t,o);try{if(!q.statSync(a).isFile())continue;const l=JSON.parse(q.readFileSync(a,"utf8"));if(l._metadata){const c=o.replace(/\.json$/,"");s.push({id:c,metadata:l._metadata})}}catch{}}return s}function Ju(e,t,r){const s=G.join(e,".codeyam","editor-scenarios",`${t}.json`);let o={};try{o=JSON.parse(q.readFileSync(s,"utf8"))}catch{return}o._metadata=r,q.writeFileSync(s,JSON.stringify(o,null,2),"utf8")}function eb(e,t,r){const s=G.join(e,".codeyam","editor-scenarios",`${t}.json`);let o={};try{o=JSON.parse(q.readFileSync(s,"utf8"))}catch{return}o._metadata&&typeof o._metadata=="object"&&(o._metadata.screenshotPath=r,o._metadata.updatedAt=new Date().toISOString(),q.writeFileSync(s,JSON.stringify(o,null,2),"utf8"))}function tb(e,t,r,s={}){const o=G.join(e,".codeyam","editor-scenarios");q.mkdirSync(o,{recursive:!0});const a=G.join(o,`${t}.json`);let i={};try{i=JSON.parse(q.readFileSync(a,"utf8"))}catch{}const l={...i,_metadata:r,...s};q.writeFileSync(a,JSON.stringify(l,null,2),"utf8")}function nb(e,t){const r=G.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const o=G.join(r,`${t}${s}`);try{q.unlinkSync(o)}catch{}}}const Pi=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Ai(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const o of Pi)try{o.ws.readyState===ri.OPEN&&(o.ws.send(r),s++)}catch{}return s}function rb(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Pi)try{r.ws.readyState===ri.OPEN&&(r.ws.send(e),t++)}catch{}return t}function Ti(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of Pi)try{s.ws.readyState===ri.OPEN&&(s.ws.send(t),r++)}catch{}return r}const sb=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:rb,broadcastPreviewRefresh:Ai,broadcastSetViewport:Ti},Symbol.toStringTag,{value:"Module"}));function ob(e){if(e.dimension)try{Ti({name:e.dimension,width:e.viewport.width,height:e.viewport.height})}catch{}Ai(e.refreshPath,e.scenarioId)}function ab(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 ib(r)}catch{return[]}}function ib(e){const t=e.trim().split(`
|
|
331
|
+
`).filter(s=>s.length>0),r=[];for(const s of t){const o=s[0],a=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,c=!1,u;if(o==="A"||a==="A")l="added",c=o==="A";else if(o==="M"||a==="M")l="modified",c=o==="M";else if(o==="D"||a==="D")l="deleted",c=o==="D";else if(o==="R"||a==="R"){l="renamed",c=o==="R";const p=i.indexOf(" -> ");p!==-1&&(u=i.slice(0,p).trim(),i=i.slice(p+4).trim())}else a==="?"?(l="untracked",c=!1):(l="modified",c=o!==" "&&o!=="?");if(i.endsWith("/")){const p=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=ee.join(p,i);try{const m=(y,g)=>{const x=de.readdirSync(y,{withFileTypes:!0}),b=[];for(const v of x){const N=ee.join(y,v.name),w=ee.relative(p,N);v.isDirectory()?b.push(...m(N,g)):v.isFile()&&b.push(w)}return b},f=m(h,p);for(const y of f)r.push({path:y,status:l,staged:c,...u&&{oldPath:u}})}catch(m){console.error(`Failed to expand directory ${i}:`,m)}}else r.push({path:i,status:l,staged:c,...u&&{oldPath:u}})}return r}function lb(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 cb(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=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(s)return s[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 db(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(`
|
|
332
|
+
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function gr(){const e=Ce();return e?ab(e):[]}function ub(){const e=Ce();return e?lb(e):null}function pb(){const e=Ce();return e?cb(e):"main"}function hb(){const e=Ce();return e?db(e):[]}function Hu(e,t){const r=Ce();return r?mb(e,t,r):[]}function mb(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
333
|
+
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let u=l[1],p,h;return c==="A"?h="added":c==="M"?h="modified":c==="D"?h="deleted":c.startsWith("R")?(h="renamed",p=l[1],u=l[2]):h="modified",{path:u,status:h,...p&&{oldPath:p}}})}catch(o){return console.error("Failed to get branch diff:",o),[]}}function Vu(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let o="";try{o=de.readFileSync(ee.join(r,e),"utf8")}catch(a){console.error(`Failed to read current file ${e}:`,a),o=""}return{oldContent:s,newContent:o,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function fb(e){const t=Ce();return t?Vu(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function gb(e,t,r,s){const o=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show ${t}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:a,newContent:i,fileName:e}}catch(a){return console.error(`Failed to get branch diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Os(e,t,r){const s=Ce();return s?gb(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}async function yb(e,t,r){const s=G.join(e,".codeyam","journal"),o=G.join(s,"index.json");G.join(s,"screenshots");let a;try{const l=await Pe.readFile(o,"utf8");a=JSON.parse(l)}catch{return}let i=!1;for(const l of a.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let c=0;c<l.scenarioScreenshots.length;c++){const u=l.scenarioScreenshots[c];if(u.name!==t)continue;const p=G.join(s,u.path);try{await Pe.copyFile(r,p),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(h){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${h instanceof Error?h.message:h}`)}}i&&Nt.notifyChange("journal")}const ic=Ni;async function xb({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json();s.url=s.url||s.path||void 0;const o=Iy({componentName:s.componentName,url:s.url,type:s.type});if(!o.valid)return new Response(JSON.stringify({error:o.error}),{status:400,headers:{"Content-Type":"application/json"}});const{name:a,description:i,componentName:l,componentPath:c}=s;if(!a)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(l&&!c)return new Response(JSON.stringify({error:`componentPath is required when componentName is provided. Add "componentPath": "app/components/${l}.tsx" (or the actual file path) to the registration JSON.`}),{status:400,headers:{"Content-Type":"application/json"}});const u=await Ye();if(!u)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:p}=await De(u),h=$e(),m=process.env.CODEYAM_ROOT_PATH||process.cwd();let f,y,g;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension&&!s.dimensions){const Q=await h.selectFrom("editor_scenarios").selectAll().where("name","=",a).where("project_id","=",p.id).orderBy("created_at","desc").executeTakeFirst();if(Q){f=Q.viewport_width||void 0,y=Q.viewport_height||void 0;try{const V=Q.dimensions?JSON.parse(Q.dimensions):void 0;Array.isArray(V)&&(g=V)}catch{}}}let x=null;s.dimensions&&s.dimensions.length>0?x=s.dimensions:s.dimension?x=[s.dimension]:g&&g.length>0&&(x=g);const b=(x==null?void 0:x[0])||void 0,v=ko({bodyWidth:s.viewportWidth||f,bodyHeight:s.viewportHeight||y,dimension:b,codeyamRoot:m});let N=null;if(!l){if(s.pageFilePath)N=s.pageFilePath;else if(s.url){const{scanPageFilePaths:Q}=await Promise.resolve().then(()=>vb),V=Ce()||process.cwd(),{allFiles:Y}=Q(V);if(N=gu(s.url,Y),!N){const B=await import("fs"),H=await import("path"),ne=["src/App.tsx","src/App.jsx","src/app/App.tsx","src/popup/App.tsx","src/pages/index.tsx","src/pages/index.jsx","src/routes/index.tsx","app/root.tsx"];for(const oe of ne)if(B.existsSync(H.join(V,oe))){N=oe;break}}}}let w=null,C=null;const S=c||N;if(S)try{await We();const V=(await tt({})||[]).filter(H=>H.filePath===S),B=V.find(H=>{var ne,oe;return((ne=H.metadata)==null?void 0:ne.notExported)===!1&&((oe=H.metadata)==null?void 0:oe.namedExport)===!1})||V[0];B&&(w=B.sha)}catch{}const k=s.type==="application"||s.type==="user";if(!w&&k&&S){const Q=Ce()||process.cwd(),V=Dy({lookupFilePath:S,scenarioType:s.type||null,projectRoot:Q});if(!V.valid)return Response.json({error:V.error},{status:400});if(V.needsAnalysis)try{const{runAnalysisForEntities:Y}=await import("./analysisRunner-RX_oAulJ.js");await Y({projectRoot:Q,filePaths:[S],onlyDataStructure:!0});try{const H=(await tt({})||[]).filter(Z=>Z.filePath===S),oe=H.find(Z=>{var re,ue;return((re=Z.metadata)==null?void 0:re.notExported)===!1&&((ue=Z.metadata)==null?void 0:ue.namedExport)===!1})||H[0];oe&&(w=oe.sha)}catch{}if(w)try{const B=await tt({});await Oy(h,(B||[]).map(H=>{var ne,oe;return{sha:H.sha,name:H.name,filePath:H.filePath||"",isDefaultExport:((ne=H.metadata)==null?void 0:ne.notExported)===!1&&((oe=H.metadata)==null?void 0:oe.namedExport)===!1}}))}catch{}}catch(Y){console.warn(`[editor-register-scenario] Auto analyze-imports failed for ${S}: ${Y.message}`)}}l?C=l:N&&N.startsWith("app/")?C=Ut($t(N)):s.url&&(C=Ct(s.url));const T=await Fy(h,{projectId:p.id,name:a,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C}),_=T.scenarioId;if(T.cleanedUpIds.length>0&&(Ry(m,T.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${T.cleanedUpIds.length} duplicate(s) for "${a}"`)),s.seedFrom&&!s.seed){const Q=await Ql(m,h,s.seedFrom);Q?(s.seed=Q,s.type||(s.type="application"),console.log(`[editor-register-scenario] Resolved seed data from "${s.seedFrom}"`)):console.warn(`[editor-register-scenario] seedFrom "${s.seedFrom}" not found — no seed data will be used`)}else if(s.seedFrom&&s.seed){const Q=await Ql(m,h,s.seedFrom);Q&&(s.seed=Xl(Q,s.seed),console.log(`[editor-register-scenario] Merged seed data: base from "${s.seedFrom}", overlay from registration`))}const $=s.type==="application"||s.type==="user",M=new Date().toISOString(),R={name:a,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||($?null:"component"),screenshotPath:null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C,createdAt:M,updatedAt:M},z={};if($&&s.seed){let Q=s.seed;if(s.type==="user"&&s.baseScenario)try{const Y=G.join(m,".codeyam","editor-scenarios",`${s.baseScenario}.json`),B=await Pe.readFile(Y,"utf-8"),H=JSON.parse(B);H.seed&&(Q=Xl(H.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(Y){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${Y instanceof Error?Y.message:Y}`)}z.type=s.type,z.seed=Q,s.externalApis&&(z.externalApis=s.externalApis),s.session&&(z.session=s.session),s.auth&&(z.auth=s.auth),s.localStorage&&(z.localStorage=s.localStorage);const V=G.join(m,".codeyam","editor-scenarios");await Pe.mkdir(V,{recursive:!0}),await Pe.writeFile(G.join(V,`${_}.seed.json`),JSON.stringify(Q,null,2))}else(s.mockData||s.localStorage)&&(s.mockData&&Object.assign(z,s.mockData),s.localStorage&&(z.localStorage=s.localStorage));let O=null;if($&&!s.seed&&Wr(m)){const V=G.join(m,".codeyam","editor-scenarios",`${_}.json`);let Y=!1;try{Y=!!JSON.parse(await Pe.readFile(V,"utf-8")).seed}catch{}Y||(O='WARNING: This application scenario has no seed data. A seed adapter exists — include "seed":{...} in registration so the page has database rows to render. Without seed data, the page will likely be empty.',console.warn(`[editor-register-scenario] ${O}`))}tb(m,_,R,z);let U=null;if($&&s.seed){const Q=Wr(m);if(Q){const V=G.join(m,".codeyam","editor-scenarios",`${_}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${Q}`);const Y=await wi(Q,V);if(U={success:Y.success,error:Y.error},Y.success){console.log(`[editor-register-scenario] Seed adapter completed in ${Y.durationMs}ms`);const B=Y.sessionCookies&&Y.sessionCookies.length>0,H=Y.externalApis&&Object.keys(Y.externalApis).length>0;if(B||H)try{const ne=G.join(m,".codeyam","editor-scenarios",`${_}.json`),oe=JSON.parse(await Pe.readFile(ne,"utf-8"));B&&(oe.sessionCookies=Y.sessionCookies),H&&(oe.externalApis={...oe.externalApis,...Y.externalApis}),await Pe.writeFile(ne,JSON.stringify(oe,null,2)),console.log("[editor-register-scenario] Saved seed adapter auth data to scenario")}catch(ne){console.warn(`[editor-register-scenario] Failed to save seed adapter auth data: ${ne}`)}}else console.warn(`[editor-register-scenario] Seed adapter failed: ${Y.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${m}/.codeyam/seed-adapter.ts`),U={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}Nt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${a}" (id: ${_})`);const W=s.url&&s.url.startsWith("/"),J=!s.url||W?await Ci():null,j=ic(),D=bi(s.url||null,J,j);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${W}, proxy=${J||"none"}, devServer=${j||"none"} → using ${D||"none"}`);let A=null,L=null,E=[],F=null,I=null,K={};if(D){const Q=Dt(a),V=await Eo({scenarioId:_,scenarioSlug:Q,scenarioType:s.type||void 0,projectRoot:m});On(),!U&&V.seedResult&&(U=V.seedResult),console.log(`[editor-register-scenario] Active scenario set to "${Q}" (${_}), type=${V.type}, seeded=${V.seeded}, seedResult=${JSON.stringify(V.seedResult??null)}, cache invalidated`),await new Promise(ue=>setTimeout(ue,300));const Y=(t=s.url)!=null&&t.startsWith("/")?`${ic()||"http://localhost:3113"}${s.url}`:D;for(let ue=0;ue<5;ue++){try{const we=await fetch(Y,{method:"GET",signal:AbortSignal.timeout(3e3)});if(we.status<500)break;console.log(`[editor-register-scenario] Route returned ${we.status}, waiting for HMR (attempt ${ue+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${ue+1}/5)...`)}await new Promise(we=>setTimeout(we,2e3))}const B=G.join(m,".codeyam","editor-scenarios","screenshots");await Pe.mkdir(B,{recursive:!0});const H=Ei(import.meta.url),ne=await _i(H,m);console.log(`[editor-register-scenario] Capture script: ${ne}`);const oe=vi(m),Z=x&&x.length>0?x:[null];K={};let re=null;for(let ue=0;ue<Z.length;ue++){const we=Z[ue];let je=v;if(we){const xe=oe[we];xe!=null&&xe.width&&(xe!=null&&xe.height)&&(je={width:xe.width,height:xe.height})}const be=we?vu(we):null,Ee=be&&Z.length>1?`${_}--${be}.png`:`${_}.png`,X=G.join(B,Ee),fe=`screenshots/${Ee}`;ue===0&&(I=je,re=X);const ae=JSON.stringify({url:D,outputPath:X,viewportWidth:je.width,viewportHeight:je.height,...l?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture ${we||"default"}: ${je.width}×${je.height} → ${Ee}`);const ie=Date.now(),he=await ji(ne,ae,m),Te=Date.now()-ie;console.log(`[editor-register-scenario] Capture ${we||"default"} ${he.success?"succeeded":"FAILED"} in ${Te}ms`),he.success||(console.warn(`[editor-register-scenario] Capture stdout: ${he.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(he.error||"").slice(0,500)}`)),ue===0&&(E=Yu(he.output),F=Zx(he.output),await Uu(m,_,a,E),E.length>0&&console.warn(`[editor-register-scenario] ${E.length} client-side error(s) detected:`,E)),he.success?(we&&(K[we]=fe),ue===0&&(A=fe)):ue===0&&(L=he.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${L}`))}if(A){try{await h.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const ue={screenshot_path:A,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(K).length>0&&(ue.screenshot_paths=JSON.stringify(K)),await h.updateTable("editor_scenarios").set(ue).where("id","=",_).execute(),Nt.notifyChange("scenario"),re&&await yb(m,a,re)}}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${a}", screenshot=${A?"captured":"skipped"}`),D&&A)try{const Q=Ce()||process.cwd(),V=G.join(Q,".codeyam","editor-step.json");let Y=null;try{const B=q.readFileSync(V,"utf8");Y=JSON.parse(B).featureStartedAt||null}catch{}if(Y){const B=Xr(Y),H=await h.selectFrom("editor_scenarios").selectAll().where("project_id","=",p.id).orderBy("created_at","asc").execute(),ne=Tt(H,Z=>`${Z.name}::${Z.url||"/"}`),oe=gr();if(oe.length>0){let Z=!1;try{const{execSync:ie}=await import("child_process"),he=ie("git rev-list --count HEAD",{cwd:Q,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();Z=parseInt(he,10)<=1}catch{Z=!0}const re=yu(oe,Z),ue={},we=G.join(Q,"app");if(q.existsSync(we)){const ie=(he,Te)=>{for(const xe of q.readdirSync(he,{withFileTypes:!0}))if(xe.name!=="isolated-components"){if(xe.isDirectory())ie(G.join(he,xe.name),Te?`${Te}/${xe.name}`:xe.name);else if(xe.name==="page.tsx"||xe.name==="page.js"){const Oe=Ct(Te?`/${Te}`:"/");ue[Oe]=Te?`app/${Te}/${xe.name}`:`app/${xe.name}`}}};ie(we,"")}let je=[];try{await We(),je=await tt({})||[]}catch{}const be=ne.map(ie=>({componentName:ie.component_name||null,componentPath:ie.component_path||null,pageFilePath:ie.page_file_path??null,url:ie.url??null,displayName:ie.display_name??null})),Ee=xu(be,ue,je),X=bu(re,Ee),fe=ne.filter(ie=>ie.created_at<B),ae=new Map;for(const ie of fe){const he=tn({componentName:ie.component_name,pageFilePath:ie.page_file_path,url:ie.url});((r=X[he])==null?void 0:r.status)==="impacted"&&ae.set(he,ie)}if(ae.size>0){console.log(`[editor-register-scenario] Recapturing ${ae.size} impacted older scenario(s): ${[...ae.keys()].join(", ")}`);const{recaptureScenarios:ie}=await Promise.resolve().then(()=>Gb),he=[...ae.values()].map(xe=>({id:xe.id,name:xe.name,url:xe.url,component_name:xe.component_name,dimensions:xe.dimensions,viewport_width:xe.viewport_width,viewport_height:xe.viewport_height}));await ie({scenarios:he,codeyamRoot:m,proxyUrl:J,devUrl:j,db:h,importMetaUrl:import.meta.url});const Te=G.join(m,".codeyam","active-scenario.json");await Pe.writeFile(Te,JSON.stringify({scenarioId:_,scenarioSlug:Dt(a),type:s.type||null,timestamp:new Date().toISOString()})),On(),Nt.notifyChange("scenario")}}}}catch(Q){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${Q instanceof Error?Q.message:Q}`)}try{const Q=new Date().toISOString(),V=Object.keys(K).length>0?K:null;Ju(m,_,{name:a,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,screenshotPath:A||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:V,pageFilePath:N,createdAt:Q,updatedAt:Q})}catch(Q){console.warn(`[editor-register-scenario] Failed to update scenario metadata (non-blocking): ${Q instanceof Error?Q.message:Q}`)}try{ob({dimension:b,viewport:v,refreshPath:s.url||void 0,scenarioId:_})}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:_,name:a,description:i,componentName:l||null,componentPath:c||null,screenshotPath:A,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:Object.keys(K).length>0?K:null},updated:!T.isNew,screenshotCaptured:A!==null,capturedViewport:I,captureError:L,clientErrors:E,...F?{visibleText:F}:{},...U?{seedResult:U}:{},...O?{missingSeedWarning:O}:{}}),{headers:{"Content-Type":"application/json"}})}catch(s){const o=s instanceof Error?s.message:String(s);return console.error("[editor-register-scenario] Error:",s),new Response(JSON.stringify({error:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const bb=Object.freeze(Object.defineProperty({__proto__:null,action:xb},Symbol.toStringTag,{value:"Module"}));function Mi(e){const t={},r=[],s=G.join(e,"app");if(!q.existsSync(s))return{map:t,allFiles:r};const o=c=>c.split("/").filter(u=>!u.startsWith("(")).join("/"),a=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),i=new Set([".tsx",".ts",".jsx",".js"]),l=(c,u)=>{for(const p of q.readdirSync(c,{withFileTypes:!0}))if(p.name!=="isolated-components")if(p.isDirectory())l(G.join(c,p.name),u?`${u}/${p.name}`:p.name);else if(p.name==="page.tsx"||p.name==="page.js"){const h=u?`app/${u}/${p.name}`:`app/${p.name}`;r.push(h);const m=o(u);t[Ct(m?`/${m}`:"/")]=h}else{if(a.has(p.name))continue;{const h=G.extname(p.name);if(!i.has(h))continue;const m=G.basename(p.name,h),f=u?`app/${u}/${p.name}`:`app/${p.name}`,y=o(u);let g;m==="index"?g=y?`/${y}`:"/":g=y?`/${y}/${m}`:`/${m}`,r.push(f);const x=Ct(g);t[x]||(t[x]=f)}}};return l(s,""),{map:t,allFiles:r}}function Ku(e){try{const t=Me("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function Gu(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=q.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function $o(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=q.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function $i(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=q.readFileSync(t,"utf8"),s=JSON.parse(r);return typeof s.step=="number"&&s.label?{step:s.step,label:s.label}:null}catch{return null}}function Fi(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=q.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.appFormats)?s.appFormats:null}catch{return null}}function qu(e){try{const t=G.join(e,".codeyam","claude-session-id.txt");return q.readFileSync(t,"utf8").trim()||null}catch{return null}}function Ri(e){try{const t=G.join(e,".codeyam","editor-user-prompt.txt");return q.readFileSync(t,"utf8").trim()||null}catch{return null}}function Qu(e){const t=G.join(e,".codeyam","active-scenario.json");try{return q.existsSync(t)&&JSON.parse(q.readFileSync(t,"utf-8")).scenarioId||null}catch{return null}}const vb=Object.freeze(Object.defineProperty({__proto__:null,detectFirstFeature:Ku,readEditorAppFormats:Fi,readEditorFeature:$o,readEditorSessionId:qu,readEditorStep:$i,readEditorUserPrompt:Ri,readFeatureStartedAt:Gu,readSavedActiveScenarioId:Qu,scanPageFilePaths:Mi},Symbol.toStringTag,{value:"Module"}));async function yr(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,a=(e.precomputedPageFilePaths??Mi(t)).map,i=new Set(Object.keys(a)),l=e.precomputedGitFiles??gr();if(l.length===0)return{entityChangeStatus:{},pageEntityNames:i};const c=Ku(t),u=yu(l,c);let p=[];if(e.precomputedEntities)p=e.precomputedEntities;else try{await We(),p=await tt({})||[]}catch{}const h=xu(r,a,p);let m=h;if(s&&s.length>0){const y=new Set(h.map(x=>x.name)),g=vy(s,y);m=[...h,...g]}return{entityChangeStatus:bu(u,m),pageEntityNames:i}}function wb(e,t,r,s){const o=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,a=[],i=[],l=new Set;for(const p of e){const h=tn({componentName:p.component_name,pageFilePath:p.page_file_path,url:p.url});if(!h)continue;const m=t[h];if(!m||p.component_name)continue;const f=p.created_at||"",y=p.updated_at||"";(o?f>=o||y>=o:!0)?(i.push({name:p.name,url:p.url,entityName:h}),l.add(h)):a.push({name:p.name,url:p.url,entityName:h,changeStatus:m.status,lastCaptured:f})}const c=[];for(const[p,h]of Object.entries(t)){if(!r.has(p)||l.has(p))continue;a.some(f=>f.entityName===p)||c.push({entityName:p,changeStatus:h.status})}const u=a.length===0&&c.length===0;return{staleScenarios:a,freshScenarios:i,uncoveredPages:c,pass:u}}async function Nb(){const e=Ce()||process.cwd(),t=await Ye();if(!t)return Response.json({error:"No project configured"},{status:400});const r=G.join(e,".codeyam","editor-step.json");let s=null;try{const f=q.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:o}=await De(t),i=await $e().selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","type","created_at","updated_at","display_name"]).where("project_id","=",o.id).orderBy("created_at","asc").execute(),l=Tt(i,f=>`${f.name}::${f.url||"/"}`),c=l.map(f=>({componentName:f.component_name||null,componentPath:f.component_path||null,pageFilePath:f.page_file_path??null,url:f.url??null,displayName:f.display_name??null}));let u={},p=new Set;try{const f=await yr({projectRoot:e,scenarioInputs:c});u=f.entityChangeStatus,p=f.pageEntityNames}catch{}if(Object.keys(u).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const h=l.map(f=>({name:f.name,component_name:f.component_name,page_file_path:f.page_file_path??null,url:f.url??null,created_at:f.created_at||"",updated_at:f.updated_at||null})),m=wb(h,u,p,s);return Response.json(m)}const Sb=Object.freeze(Object.defineProperty({__proto__:null,loader:Nb},Symbol.toStringTag,{value:"Module"}));function Cb({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const o=ce(i=>t.some(l=>l.flowId===i),[t]),a=ce(i=>{o(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,o]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=o(i.id),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>a(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),d("div",{className:"flex-1 min-w-0",children:[d("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}),!c&&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&&d("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((u,p)=>d("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:u.attributePath})," ",n("span",{className:"text-gray-400",children:u.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:u.value})]},p))})]})]},i.id)})})}function Di(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const o=[];t.forEach(c=>{var p;const u=((p=c.metadata)==null?void 0:p.coveredFlows)||[];u.forEach(h=>{const m=s.get(h);m&&m.usedInScenarios.push({id:c.id||"",name:c.name})}),o.push({scenario:c,coveredFlowIds:u})});const a=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=a>0?i/a*100:0;return{executionFlows:r,totalFlows:a,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:o}}function kb(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Eb=({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 _b({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await mo(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(i=s.scenarios)==null?void 0:i.find(l=>l.name===ho);if(!o)throw new Response("Default scenario not found",{status:404});const a=await Ye();return le({analysis:s,defaultScenario:o,entity:s.entity,entitySha:t,projectSlug:a})}function jb(){var D;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:o}=lt(),a=zt(),{iframeRef:i}=ki(),[l,c]=P(""),[u,p]=P(400),[h,m]=P(!1),[f,y]=P(!1),[g,x]=P(!1),[b,v]=P(null),[N,w]=P(null),[C,S]=P([]),k=pe(()=>{var L;return!((L=e==null?void 0:e.metadata)!=null&&L.executionFlows)||!(e!=null&&e.scenarios)?[]:Di(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:T,isStarting:_,isLoading:$,showIframe:M,iframeKey:R,onIframeLoad:z}=Bn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:o,enabled:!0}),O=ce(async()=>{var A,L,E,F;if(!l.trim()&&C.length===0){v("Please describe how you want to change the scenario or select execution flows");return}y(!0),v(null),w("Generating scenario with AI...");try{const I=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(A=e.metadata)==null?void 0:A.scenariosDataStructure,flowSelections:C.length>0?C:void 0})}),K=await I.json();if(!I.ok||!K.success)throw new Error(K.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",K.data);const Q=K.data;if(!Q.name||!Q.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const V={name:Q.name,description:Q.description||l,metadata:{data:Q.data,interactiveExamplePath:(L=t.metadata)==null?void 0:L.interactiveExamplePath}},Y=[...e.scenarios||[],V],B=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:Y})}),H=await B.json();if(!B.ok||!H.success)throw new Error(H.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",H);const ne=(F=(E=H.analysis)==null?void 0:E.scenarios)==null?void 0:F.find(oe=>oe.name===Q.name);if(!(ne!=null&&ne.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void a(`/entity/${s}`),1e3);return}if(T){w("Capturing screenshot...");const oe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:T,scenarioId:ne.id,projectId:e.projectId,viewportWidth:1440})}),Z=await oe.json();!oe.ok||!Z.success?(console.error("[CreateScenario] Capture failed:",Z),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{a(`/entity/${s}/scenarios/${ne.id}`)},1e3)}catch(I){console.error("[CreateScenario] Error:",I),v(I instanceof Error?I.message:String(I)),w(null)}finally{y(!1),x(!1)}},[l,C,e,t,s,T,a]),U=f||g,W=ce(()=>{m(!0)},[]),J=ce(A=>{if(!h)return;const L=A.clientX;L>=250&&L<=600&&p(L)},[h]),j=ce(()=>{m(!1)},[]);return se(()=>(h?(document.addEventListener("mousemove",J),document.addEventListener("mouseup",j)):(document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",j)),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",j)}),[h,J,j]),d("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:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void a(`/entity/${s}`),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})]}),d("div",{className:"flex items-end gap-8 shrink-0",children:[n(ke,{to:`/entity/${s}/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:d("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:((D=e==null?void 0:e.scenarios)==null?void 0:D.length)||0})]})}),n(ke,{to:`/entity/${s}/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(ke,{to:`/entity/${s}/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(ke,{to:`/entity/${s}/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(ke,{to:`/entity/${s}/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"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${u}px`},children:[d("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&&d("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[d("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"," ",C.length>0&&d("span",{className:"text-blue-600",children:["(",C.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Cb,{executionFlows:k,selections:C,onChange:S,disabled:U})})]}),d("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:A=>c(A.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:U})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void O(),disabled:U||!l.trim()&&C.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:U?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),d("div",{onMouseDown:W,style:{width:"20px",position:"absolute",top:0,left:`${u-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
334
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
335
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
336
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
337
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
338
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Mo,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:T,isStarting:_,isLoading:$,showIframe:M,iframeKey:R,onIframeLoad:z,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Pb=nt(function(){return n(To,{children:n(jb,{})})}),Ab=Object.freeze(Object.defineProperty({__proto__:null,default:Pb,loader:_b,meta:Eb},Symbol.toStringTag,{value:"Module"})),Tb=Ni;async function Mb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:o,viewportHeight:a}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Ye();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await De(i),c=$e(),u=await c.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!u)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const p=s??u.url??null,h=p&&p.startsWith("/"),m=!p||h?await Ci():null,f=Tb(),y=bi(p,m,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${u.url||"none"}, proxy=${m||"none"}, devServer=${f||"none"} → captureUrl=${y||"none"}`),!y)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${u.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Dt(u.name);await Eo({scenarioId:r,scenarioSlug:x,scenarioType:u.type||void 0,projectRoot:g}),On(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(M=>setTimeout(M,300));const b=G.join(g,".codeyam","editor-scenarios","screenshots");await Pe.mkdir(b,{recursive:!0});const v=Ei(import.meta.url),N=await _i(v,g);console.log(`[editor-capture-scenario] Capture script: ${N}`);let w;const C=u;if(t.dimensions&&t.dimensions.length>0)w=t.dimensions;else if(C.dimensions)try{const M=typeof C.dimensions=="string"?JSON.parse(C.dimensions):C.dimensions;w=Array.isArray(M)&&M.length>0?M:[null]}catch{w=[null]}else w=[null];const S=vi(g);let k=null;const T={};let _=[],$=null;for(let M=0;M<w.length;M++){const R=w[M];let z;R&&S[R]?z=S[R]:z=ko({bodyWidth:o||C.viewport_width||void 0,bodyHeight:a||C.viewport_height||void 0,dimension:R||void 0,codeyamRoot:g});const O=R?vu(R):null,U=O&&w.length>1?`${r}--${O}.png`:`${r}.png`,W=G.join(b,U),J=`screenshots/${U}`,j=JSON.stringify({url:y,outputPath:W,viewportWidth:z.width,viewportHeight:z.height,...u.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Capture ${R||"default"}: ${z.width}×${z.height} → ${U}`);const D=Date.now(),A=await ji(N,j,g),L=Date.now()-D;if(console.log(`[editor-capture-scenario] Capture ${R||"default"} ${A.success?"succeeded":"FAILED"} in ${L}ms`),!A.success){console.warn(`[editor-capture-scenario] Capture stdout: ${A.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(A.error||"").slice(0,500)}`),M===0&&($=A.error||"Unknown capture error");continue}if(M===0){k=J;const E=Yu(A.output);_=E,await Uu(g,r,u.name,E)}R&&(T[R]=J)}if(!k&&$)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:$}),{status:500,headers:{"Content-Type":"application/json"}});if(k){try{await c.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const M={screenshot_path:k,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(T).length>0&&(M.screenshot_paths=JSON.stringify(T)),await c.updateTable("editor_scenarios").set(M).where("id","=",r).execute()}return _.length>0&&console.warn(`[editor-capture-scenario] ${_.length} client-side error(s) detected:`,_),Nt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:k,screenshotPaths:Object.keys(T).length>0?T:null,clientErrors:_}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const $b=Object.freeze(Object.defineProperty({__proto__:null,action:Mb},Symbol.toStringTag,{value:"Module"}));async function Fb({request:e,params:t}){const r=t["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),o=ee.join(s,".codeyam","editor-scenarios","screenshots",r),a=ee.resolve(o),i=ee.resolve(ee.join(s,".codeyam","editor-scenarios","screenshots"));if(!a.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Ae.stat(o),c=`"${l.mtimeMs}-${l.size}"`;if(e.headers.get("If-None-Match")===c)return new Response(null,{status:304,headers:{ETag:c,"Cache-Control":"public, max-age=300"}});const p=await Ae.readFile(o),h=ee.extname(o).toLowerCase(),m=h===".png"?"image/png":h===".jpg"||h===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(p,{status:200,headers:{"Content-Type":m,"Cache-Control":"public, max-age=300",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const Rb=Object.freeze(Object.defineProperty({__proto__:null,loader:Fb},Symbol.toStringTag,{value:"Module"}));async function Db({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","journal","screenshots",t),o=ee.resolve(s),a=ee.resolve(ee.join(r,".codeyam","journal","screenshots"));if(!o.startsWith(a))return new Response("Invalid path",{status:403});try{const i=await Ae.readFile(s),l=ee.extname(s).toLowerCase(),c=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"no-store"}})}catch{return new Response("Image not found",{status:404})}}const Ib=Object.freeze(Object.defineProperty({__proto__:null,loader:Db},Symbol.toStringTag,{value:"Module"})),Ob=["JSX","React","Element","ReactNode"],Lb=new Set(["page.tsx","page.ts","index.tsx","index.ts"]);function zb(e){if(e.returnType&&Ob.some(t=>e.returnType.includes(t)))return!0;if(e.filePath){const t=e.filePath.split("/").pop()||"";if(Lb.has(t))return!0}return!1}function Bb(e){const t=[],r=[];for(const s of e)zb(s)?t.push(s):r.push(s);return{components:t,functions:r}}function ua({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:o,clientErrors:a,totalScenarioCounts:i,entityChangeStatus:l,analysisFailedEntities:c,testCaseCounts:u}){const p=e.map(k=>{const T=r[k.name]||0,_=(i==null?void 0:i[k.name])||0,$=l==null?void 0:l[k.name],M=a==null?void 0:a[k.name],R=T>0&&M&&M.length>0;let z;c!=null&&c.has(k.name)?z="analysis_failed":T===0?$&&_>0?z="needs_recapture":z="missing":R?z="has_errors":z="ok";let O;if(z==="missing"){const U=k.filePath.split("/").pop()||"";U==="layout.tsx"||U==="layout.ts"?O=`This is a layout file — register an app-level scenario with pageFilePath instead of componentName: codeyam editor register '{"name":"${k.name} - Default","pageFilePath":"${k.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:U==="page.tsx"||U==="page.ts"?O=`This is a page file — register an app-level scenario with pageFilePath: codeyam editor register '{"name":"${k.name} - Default","pageFilePath":"${k.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:O=`Register a component scenario via an isolation route: codeyam editor isolate ${k.name} then codeyam editor register '{"name":"${k.name} - Default","componentName":"${k.name}","url":"/isolated-components/${k.name}?s=Default","dimensions":["Desktop"]}'`}else z==="needs_recapture"?O=`This component's code or dependencies changed — recapture existing scenarios to update screenshots: codeyam editor recapture ${k.name}`:z==="analysis_failed"&&(O="Analysis failed for this component (likely timed out due to complex dependencies). The component has partial data but may be missing some dependency schemas. Try re-analyzing: codeyam editor analyze-imports");return{name:k.name,filePath:k.filePath,scenarioCount:z==="needs_recapture"?_:T,status:z,...R?{clientErrors:M}:{},...O?{hint:O}:{}}}),h=t.map(k=>{if(!(k.testFile?s[k.testFile]??!1:!1)){const R=k.testFile?void 0:k.filePath.replace(/\.tsx?$/,".test.ts");return{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!1,status:"missing",...R?{suggestedTestFile:R}:{}}}const _=k.testFile&&o?o[k.testFile]:void 0;if(!_)return{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!0,status:"ok"};let $;!_.passing&&_.errorMessage?$="runner_error":_.passing?_.hasEntityNameDescribe?$="ok":$="name_mismatch":$="failing";let M;return $==="name_mismatch"?M=`Tests pass but won't show in the CodeYam UI. Add a top-level describe("${k.name}", ...) block in ${k.testFile}`:$==="runner_error"&&_.errorMessage&&(M=`Test runner crashed (not a test failure): ${_.errorMessage}`),{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!0,testsPassing:_.passing,testsVisibleInUi:_.hasEntityNameDescribe,status:$,..._.errorMessage?{errorMessage:_.errorMessage}:{},...M?{hint:M}:{},...(u==null?void 0:u[k.name])!==void 0?{testCaseCount:u[k.name]}:{}}}),m=p.filter(k=>k.status==="ok").length,f=p.filter(k=>k.status==="has_errors").length,y=p.filter(k=>k.status==="missing").length,g=p.filter(k=>k.status==="needs_recapture").length,x=p.filter(k=>k.status==="analysis_failed").length,b=h.filter(k=>k.status==="ok").length,v=h.filter(k=>k.status==="failing").length,N=h.filter(k=>k.status==="runner_error").length,w=h.filter(k=>k.status==="name_mismatch").length,C=h.filter(k=>k.status==="missing").length,S=h.filter(k=>k.status==="ok"&&k.testCaseCount!==void 0&&k.testCaseCount<3).length;return{components:p,functions:h,summary:{totalComponents:p.length,componentsOk:m,componentsMissing:y,componentsWithErrors:f,componentsNeedingRecapture:g,componentsAnalysisFailed:x,totalFunctions:h.length,functionsOk:b,functionsMissing:C,functionsFailing:v,functionsRunnerError:N,functionsNameMismatch:w,functionsThinCoverage:S,allPassing:y===0&&f===0&&x===0&&v===0&&N===0&&w===0&&C===0}}}function Yb({featureStartedAt:e,entityChangeStatus:t}){return t&&Object.keys(t).length>0?{featureStartedAt:e,entityChangeStatus:t}:{featureStartedAt:null,entityChangeStatus:t}}function Ub(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function Wb(e,t,r){const o=await e.selectFrom("editor_scenarios").select(["entity_sha"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("entity_sha","is not",null).groupBy("entity_sha").execute();if(o.length===0)return[];const a=o.map(w=>w.entity_sha),i=await e.selectFrom("analyses").select("entity_sha").where("entity_sha","in",a).groupBy("entity_sha").execute(),l=new Set(i.map(w=>w.entity_sha)),c=o.filter(w=>!l.has(w.entity_sha));if(c.length===0)return[];const u=c.map(w=>w.entity_sha),p=await e.selectFrom("entities").select(["sha","name","file_path"]).where("sha","in",u).execute(),h=new Map(p.map(w=>[w.sha,w.name])),m=new Map(p.map(w=>[w.sha,w.file_path])),f=[...new Set(p.map(w=>`${w.name}::${w.file_path}`).filter(w=>!w.startsWith("::")&&!w.endsWith("::")))];let y=new Set;if(f.length>0){const w=[...new Set(p.map(S=>S.name).filter(Boolean))],C=await e.selectFrom("entities").innerJoin("analyses","analyses.entity_sha","entities.sha").select(["entities.name","entities.file_path"]).where("entities.name","in",w).groupBy(["entities.name","entities.file_path"]).execute();y=new Set(C.map(S=>`${S.name}::${S.file_path}`))}const g=c.filter(w=>{const C=w.entity_sha,S=h.get(C),k=m.get(C);if(!S)return!1;const T=`${S}::${k}`;return!y.has(T)});if(g.length===0)return[];const x=g.map(w=>w.entity_sha),b=await e.selectFrom("editor_scenarios").select(["entity_sha","component_name"]).where("project_id","=",t).where("entity_sha","in",x).where("component_name","is not",null).groupBy("entity_sha").execute(),v=new Map(b.map(w=>[w.entity_sha,w.component_name]));let N=new Set;if(r){const w=r.replace("T"," ").replace(/\.\d{3}Z$/,""),C=await e.selectFrom("editor_scenarios").select("entity_sha").where("project_id","=",t).where("entity_sha","in",x).where(S=>S.or([S("created_at",">=",w),S("updated_at",">=",w)])).groupBy("entity_sha").execute();N=new Set(C.map(S=>S.entity_sha))}return g.map(w=>{const C=w.entity_sha;return{entitySha:C,name:h.get(C)||v.get(C)||"Unknown",scenarioCount:Number(w.count),preExisting:r?!N.has(C):!1}})}async function Jb(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name","name","url"]).where("project_id","=",t).where("component_name","is not",null).where("url","is not",null);if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const a=(await s.execute()).filter(l=>l.url&&!So(l.url));if(a.length===0)return[];const i=new Map;for(const l of a){const c=`${l.component_name}::${l.url}`,u=i.get(c);u?u.scenarioNames.push(l.name):i.set(c,{componentName:l.component_name,scenarioNames:[l.name],url:l.url})}return[...i.values()]}async function lc(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is not",null).groupBy("component_name");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const o=await s.execute(),a={};for(const i of o)i.component_name&&(a[i.component_name]=Number(i.count));return a}async function cc(e,t,r){let s=e.selectFrom("editor_scenarios").select(["page_file_path"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is",null).where("page_file_path","is not",null).groupBy("page_file_path");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const o=await s.execute(),a={};for(const i of o)i.page_file_path&&(a[i.page_file_path]=Number(i.count));return a}async function Hb(e,t,r){var i;let s=e.selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path","name"]).where("project_id","=",t).where("entity_sha","is",null).where(l=>l.or([l("component_path","is not",null),l("page_file_path","is not",null)]));if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const o=await s.execute();if(o.length===0)return[];const a=new Map;for(const l of o){const c=l,u=c.component_path||c.page_file_path,p=a.get(u);if(p)p.scenarioNames.push(c.name);else{const h=c.component_name||((i=u.split("/").pop())==null?void 0:i.replace(/\.\w+$/,""))||u;a.set(u,{name:h,filePath:u,scenarioNames:[c.name]})}}return[...a.values()].map(l=>({name:l.name,filePath:l.filePath,scenarioCount:l.scenarioNames.length,scenarioNames:l.scenarioNames}))}function Vb(e){const t=new Map;for(const r of e){const s=t.get(r.name);s?s.push(r):t.set(r.name,[r])}for(const[r,s]of t)s.length<=1&&t.delete(r);return t}function Zu(e){const{scenarios:t,entityChangeStatus:r}=e;if(!r||Object.keys(r).length===0)return[];const s=[];for(const o of t){if(o.updatedInSession||!o.entityName)continue;const a=r[o.entityName];a&&a.status!=="new"&&s.push({scenarioName:o.name,entityName:o.entityName,status:a})}return s}function Kb(e,t){const r={},s=new Map;for(const o of t){const a=tn({componentName:o.componentName,pageFilePath:o.pageFilePath,url:o.url});a&&s.set(o.name,a)}for(const[,o]of Object.entries(e)){if(o.errors.length===0)continue;let a=s.get(o.scenarioName);if(!a){const i=o.scenarioName.indexOf(" - ");a=i>=0?o.scenarioName.slice(0,i):o.scenarioName}a&&(r[a]||(r[a]=[]),r[a].push(...o.errors))}return r}async function Xu(e){const{scenarios:t,codeyamRoot:r,proxyUrl:s,devUrl:o,db:a,importMetaUrl:i,onProgress:l}=e,c={recaptured:[],failed:[]};if(t.length===0)return c;const u=Ei(i),p=await _i(u,r),h=G.join(r,".codeyam","editor-scenarios","screenshots");for(const m of t)try{const f=Dt(m.name);await Eo({scenarioId:m.id,scenarioSlug:f,projectRoot:r}),On(),await new Promise(w=>setTimeout(w,300));const y=bi(m.url||null,s,o);if(!y){c.failed.push({name:m.name,error:"No capture URL available"});continue}const g=G.join(h,`${m.id}.png`);let x;try{const w=m.dimensions?JSON.parse(m.dimensions):null;Array.isArray(w)&&w.length>0&&(x=w[0])}catch{}const b=ko({bodyWidth:m.viewport_width||void 0,bodyHeight:m.viewport_height||void 0,dimension:x,codeyamRoot:r}),v=JSON.stringify({url:y,outputPath:g,viewportWidth:b.width,viewportHeight:b.height,...m.component_name?{selector:"#codeyam-capture"}:{}});l==null||l(`Capturing "${m.name}"...`),console.log(`[recapture] Capturing "${m.name}" at ${b.width}x${b.height}`);const N=await ji(p,v,r);if(N.success)await a.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${m.id}.png`,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",m.id).execute(),c.recaptured.push(m.name),l==null||l(`Recaptured "${m.name}"`),console.log(`[recapture] Succeeded: "${m.name}"`);else{const w=N.error||"Unknown capture error";c.failed.push({name:m.name,error:w}),l==null||l(`Failed: "${m.name}" — ${w}`),console.warn(`[recapture] Failed: "${m.name}": ${w}`)}}catch(f){const y=f instanceof Error?f.message:String(f);c.failed.push({name:m.name,error:y}),console.warn(`[recapture] Error for "${m.name}": ${y}`)}return c}const Gb=Object.freeze(Object.defineProperty({__proto__:null,recaptureScenarios:Xu},Symbol.toStringTag,{value:"Module"}));async function qb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await Ye();if(!r)return Response.json({error:"No project configured"},{status:400});const{project:s}=await De(r),o=$e(),a=process.env.CODEYAM_ROOT_PATH||process.cwd(),i=G.join(t,".codeyam","editor-step.json");let l=null;try{const C=q.readFileSync(i,"utf8");l=JSON.parse(C).featureStartedAt||null}catch{}try{await We();const C=await tt({})||[];await wu(o,C.map(S=>{var k,T;return{sha:S.sha,name:S.name,filePath:S.filePath||"",isDefaultExport:((k=S.metadata)==null?void 0:k.notExported)===!1&&((T=S.metadata)==null?void 0:T.namedExport)===!1}}))}catch{}const c=await o.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","display_name","dimensions","viewport_width","viewport_height","created_at","updated_at"]).where("project_id","=",s.id).orderBy("created_at","asc").execute(),u=Tt(c,C=>`${C.name}::${C.url||"/"}`),p=u.map(C=>({componentName:C.component_name||null,componentPath:C.component_path||null,pageFilePath:C.page_file_path??null,url:C.url??null,displayName:C.display_name??null})),{entityChangeStatus:h}=await yr({projectRoot:t,scenarioInputs:p});if(Object.keys(h).length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"No entity changes detected."});const m=l?Xr(l):null,f=u.map(C=>({name:C.name,entityName:tn({componentName:C.component_name,pageFilePath:C.page_file_path,url:C.url}),updatedInSession:m?xi({created_at:C.created_at,updated_at:C.updated_at},m):!1})),y=Zu({scenarios:f,entityChangeStatus:h});if(y.length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"All scenarios are up to date."});const g=new Set(y.map(C=>C.scenarioName)),x=u.filter(C=>g.has(C.name)).map(C=>({id:C.id,name:C.name,url:C.url,component_name:C.component_name,dimensions:C.dimensions,viewport_width:C.viewport_width,viewport_height:C.viewport_height})),b=await Ci(),v=Ni(),N=new Map(u.map(C=>[C.name,C])),w=new ReadableStream({async start(C){const S=T=>{C.enqueue(new TextEncoder().encode(JSON.stringify(T)+`
|
|
339
|
+
`))};S({type:"start",total:y.length});const k=await Xu({scenarios:x,codeyamRoot:a,proxyUrl:b,devUrl:v,db:o,importMetaUrl:import.meta.url,onProgress:T=>{if(T.startsWith('Recaptured "')){const _=T.slice(12,-1);S({type:"success",name:_});const $=N.get(_);if($)try{eb(a,$.id,`screenshots/${$.id}.png`)}catch{}}else if(T.startsWith('Failed: "')){const _=T.match(/^Failed: "(.+?)" — (.+)$/);_&&S({type:"failure",name:_[1],error:_[2]})}else if(T.startsWith('Capturing "')){const _=T.slice(11,T.indexOf('"',11));S({type:"capturing",name:_})}}});S({type:"done",recaptured:k.recaptured,failed:k.failed,total:y.length}),C.close()}});return new Response(w,{headers:{"Content-Type":"application/x-ndjson","Transfer-Encoding":"chunked"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-recapture-stale] Error:",t),Response.json({error:r},{status:500})}}const Qb=Object.freeze(Object.defineProperty({__proto__:null,action:qb},Symbol.toStringTag,{value:"Module"}));async function Zb({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,name:s}=t;if(!r||!(s!=null&&s.trim()))return Response.json({error:"Missing required fields: scenarioId, name"},{status:400});const o=s.trim();await $e().updateTable("editor_scenarios").set({name:o,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",r).execute();const l=Ce()||process.cwd(),u=Xx(l).find(p=>p.id===r);return u&&Ju(l,r,{...u.metadata,name:o,updatedAt:new Date().toISOString()}),Response.json({success:!0,name:o})}catch(t){return console.error("[API] Error renaming scenario:",t),Response.json({error:"Failed to rename scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Xb=Object.freeze(Object.defineProperty({__proto__:null,action:Zb},Symbol.toStringTag,{value:"Module"}));async function ev({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=t.mode||"overwrite",s=t.localStorage,o=Ce()||process.cwd(),a=ee.join(o,".codeyam"),i=ee.join(a,"active-scenario.json");if(!de.existsSync(i))return new Response(JSON.stringify({error:"No active scenario"}),{status:400,headers:{"Content-Type":"application/json"}});const c=JSON.parse(de.readFileSync(i,"utf-8")).scenarioId;if(!c)return new Response(JSON.stringify({error:"No active scenario ID"}),{status:400,headers:{"Content-Type":"application/json"}});const u=ee.join(a,"editor-scenarios"),p=Wr(o);let h=null;if(p){const f=ee.join(a,"tmp",`export-${Date.now()}.json`);de.mkdirSync(ee.dirname(f),{recursive:!0});const y=await Vy(p,f);if(!y.success)return new Response(JSON.stringify({error:`Export failed: ${y.error}`}),{status:500,headers:{"Content-Type":"application/json"}});try{h=JSON.parse(de.readFileSync(f,"utf-8"))}finally{try{de.unlinkSync(f)}catch{}}}if(!h&&!s)return new Response(JSON.stringify({error:"No data to save: no seed adapter found and no localStorage provided"}),{status:400,headers:{"Content-Type":"application/json"}});let m=c;if(r==="new"){m=dr.randomUUID();const f=ee.join(u,`${c}.json`);let y={_metadata:{type:"application"}};de.existsSync(f)&&(y=JSON.parse(de.readFileSync(f,"utf-8"))),h&&(y.seed=h),s&&(y.localStorage=s),de.writeFileSync(ee.join(u,`${m}.json`),JSON.stringify(y,null,2)),h&&de.writeFileSync(ee.join(u,`${m}.seed.json`),JSON.stringify(h,null,2))}else{const f=ee.join(u,`${c}.json`);if(de.existsSync(f)){const y=JSON.parse(de.readFileSync(f,"utf-8"));h&&(y.seed=h),s&&(y.localStorage=s),de.writeFileSync(f,JSON.stringify(y,null,2))}h&&de.writeFileSync(ee.join(u,`${c}.seed.json`),JSON.stringify(h,null,2))}return On(),new Response(JSON.stringify({success:!0,mode:r,scenarioId:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const tv=Object.freeze(Object.defineProperty({__proto__:null,action:ev},Symbol.toStringTag,{value:"Module"}));async function nv({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});const t=await e.json(),{prompt:r}=t;if(!r)return Response.json({error:"Missing prompt"},{status:400});const s=Ce()||process.cwd(),o=G.join(s,".codeyam","tmp");q.mkdirSync(o,{recursive:!0});const a=Za.randomUUID().slice(0,8),i=G.join(o,`scenario-prompt-${a}.md`);return q.writeFileSync(i,r,"utf8"),Response.json({promptFile:i})}const rv=Object.freeze(Object.defineProperty({__proto__:null,action:nv},Symbol.toStringTag,{value:"Module"}));let _n=null;async function sv({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:o,scenarioType:a,skipBroadcast:i}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=Ce()||process.cwd(),c=ee.join(l,".codeyam"),u=ee.join(c,"active-scenario.json");let p=a||null;if(!p&&s){const x=ee.join(c,"editor-scenarios",`${s}.json`);try{de.existsSync(x)&&(p=JSON.parse(de.readFileSync(x,"utf-8")).type||null)}catch{}}let h=null;try{de.existsSync(u)&&(h=JSON.parse(de.readFileSync(u,"utf-8")).scenarioId||null)}catch{}const m=h===s&&s!==null;de.mkdirSync(c,{recursive:!0}),de.writeFileSync(u,JSON.stringify({scenarioSlug:r,scenarioName:o||null,scenarioId:s||null,type:p,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let f=null;const y=p==="application"||p==="user";if(y&&s&&m)console.log(`[editor-switch-scenario] Same scenario "${r}" already active — skipping seed`),f={success:!0};else if(y&&s)if(_n&&_n.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),f=await _n.promise;else{const x=Wr(l),b=ee.join(c,"editor-scenarios",`${s}.seed.json`);if(x&&de.existsSync(b)){console.log(`[editor-switch-scenario] Running seed adapter for ${p} scenario "${o||r}"`);const v=wi(x,b).then(N=>{const w={success:N.success,error:N.error};if(N.success){console.log(`[editor-switch-scenario] Seed adapter completed in ${N.durationMs}ms`);const C=N.sessionCookies&&N.sessionCookies.length>0,S=N.externalApis&&Object.keys(N.externalApis).length>0;if(C||S)try{const k=ee.join(c,"editor-scenarios",`${s}.json`);if(de.existsSync(k)){const T=JSON.parse(de.readFileSync(k,"utf-8"));C&&(T.sessionCookies=N.sessionCookies),S&&(T.externalApis={...T.externalApis,...N.externalApis}),de.writeFileSync(k,JSON.stringify(T,null,2))}}catch{}}else console.warn(`[editor-switch-scenario] Seed adapter failed: ${N.error}`);return w});_n={scenarioId:s,promise:v};try{f=await v}finally{_n&&_n.scenarioId===s&&(_n=null)}}else x||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),f={success:!1,error:"No seed adapter found"})}On();const g=i?0:Ai();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:g,seeded:y,...f?{seedResult:f}:{}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const ov=Object.freeze(Object.defineProperty({__proto__:null,action:sv},Symbol.toStringTag,{value:"Module"}));var _e;(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={}))})(_e||(_e={}));function ep(e,t){return e?Object.values(_e.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const tp=ep(process.env.DEFAULT_SMALLER_MODEL,_e.Model.OPENAI_GPT4_1_MINI),av=ep(process.env.DEFAULT_LARGER_MODEL,_e.Model.OPENAI_GPT4_1),Rt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},pa={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},iv={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},ha={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},dn={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},lv={[_e.Model.OPENAI_GPT5_1]:{id:_e.Model.OPENAI_GPT5_1,provider:Rt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[_e.Model.OPENAI_GPT5]:{id:_e.Model.OPENAI_GPT5,provider:Rt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[_e.Model.OPENAI_GPT5_MINI]:{id:_e.Model.OPENAI_GPT5_MINI,provider:Rt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[_e.Model.OPENAI_GPT5_NANO]:{id:_e.Model.OPENAI_GPT5_NANO,provider:Rt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[_e.Model.OPENAI_GPT4_1]:{id:_e.Model.OPENAI_GPT4_1,provider:Rt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[_e.Model.OPENAI_GPT4_1_MINI]:{id:_e.Model.OPENAI_GPT4_1_MINI,provider:Rt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[_e.Model.OPENAI_GPT4_O]:{id:_e.Model.OPENAI_GPT4_O,provider:Rt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[_e.Model.OPENAI_GPT4_O_MINI]:{id:_e.Model.OPENAI_GPT4_O_MINI,provider:Rt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[_e.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:_e.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:pa,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[_e.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:_e.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:pa,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[_e.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:_e.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:pa,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[_e.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:_e.Model.OPENAI_GPT_OSS_120B_GROQ,provider:iv,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[_e.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:_e.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:dn,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[_e.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:_e.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:dn,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[_e.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:_e.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:dn,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[_e.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:_e.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:dn,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[_e.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:_e.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:dn,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[_e.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:_e.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:ha,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[_e.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:_e.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:ha,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[_e.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:_e.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:ha,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[_e.Model.PHIND_CODELLAMA]:{id:_e.Model.PHIND_CODELLAMA,provider:Rt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[_e.Model.GOOGLE_GEMINI_PRO]:{id:_e.Model.GOOGLE_GEMINI_PRO,provider:dn,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[_e.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:_e.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:dn,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[_e.Model.META_CODELLAMA_34B_INSTRUCT]:{id:_e.Model.META_CODELLAMA_34B_INSTRUCT,provider:dn,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[_e.Model.OPENAI_GPT4_PREVIEW]:{id:_e.Model.OPENAI_GPT4_PREVIEW,provider:Rt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Fo(e){const t=lv[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function cv(e){return Fo(e).maxCompletionTokens}function dv(e){return Fo(e).pricing}const dc=1e6;function uv({model:e,usage:t}){const r=dv(e);return r?t.prompt_tokens*(r.input/dc)+t.completion_tokens*(r.output/dc):null}function pv({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 s=t.usage||{prompt_tokens:0,completion_tokens:0},o=uv({model:r,usage:s});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:s.prompt_tokens,output_tokens:s.completion_tokens,cost:o?Math.round(o*1e5)/1e5:void 0}}function hv({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:o}){const a=r??tp,i=Fo(a);cv(a);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:s==="json_schema"&&o?{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}let Lr=null;function mv(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;try{const t=Yr(e,".codeyam","secrets.json");if(Pt(t)){const s=JSON.parse(Rl(t,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}const r=Yr(Em(),".codeyam","secrets.json");if(Pt(r)){const s=JSON.parse(Rl(r,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}return!!(process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.GROQ_API_KEY)}catch{return!1}}function fv(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;const t=Yr(e,".claude");return Pt(t)}function R_(e){if(mv(e))return Lr={mode:"direct-api",projectRoot:e},"direct-api";if(fv(e))return Lr={mode:"claude-cli",projectRoot:e},"claude-cli";throw new Error(`No AI service configured. Please either:
|
|
340
|
+
1. Add an API key to ~/.codeyam/secrets.json (shared across projects) or .codeyam/secrets.json (project-specific), or
|
|
341
|
+
2. Use Claude Code CLI (detected by .claude folder)`)}function gv(){return(Lr==null?void 0:Lr.mode)==="claude-cli"}const Oa="/tmp/codeyam-e2e-tracking";let ma,fa;function yv(){return ma===void 0&&(ma=process.env.CODEYAM_E2E_TRACK_DATA==="true"),ma}function xv(){return fa===void 0&&(fa=!process.env.CODEYAM_LLM_FIXTURES_DIR),fa}function bv(){q.existsSync(Oa)||q.mkdirSync(Oa,{recursive:!0})}function vv(e){const t=JSON.stringify(e,null,0);return Za.createHash("md5").update(t).digest("hex")}function wv(e,t,r){return[e].join("_")+".json"}function np(e,t,r,s){if(!yv())return;bv();const o=wv(e),a=G.join(Oa,o),i=vv(t);if(xv()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};q.writeFileSync(a,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(q.existsSync(a)){const l=JSON.parse(q.readFileSync(a,"utf-8")),c={matches:i===l.dataHash,firstRunHash:l.dataHash};if(c.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{c.differences=La(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const u=a.replace(".json","_DIFF.json");q.writeFileSync(u,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${u}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function La(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const o=Math.max(e.length,t.length);for(let a=0;a<o;a++)s.push(...La(e[a],t[a],`${r}[${a}]`));return s}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),a=Object.keys(t),i=Array.from(new Set([...o,...a]));for(const l of i){const c=e[l],u=t[l];l in e?l in t?s.push(...La(c,u,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const o=JSON.stringify(e),a=JSON.stringify(t);o.length<100&&a.length<100?s.push(`${r||"root"}: ${o} vs ${a}`):s.push(`${r||"root"}: values differ (${o.length} chars vs ${a.length} chars)`)}return s}const uc=ti(ei),pc=2;function Nv(e){try{return JSON.parse(e),{valid:!0}}catch(t){return{valid:!1,error:t.message}}}function Sv(e){const t=e.trim(),r=(t.match(/\{/g)||[]).length,s=(t.match(/\}/g)||[]).length,o=(t.match(/\[/g)||[]).length,a=(t.match(/\]/g)||[]).length,i=(t.match(new RegExp('(?<!\\\\)"',"g"))||[]).length;return r>s||o>a||i%2!==0||!t.endsWith("}")&&!t.endsWith("]")}async function rp(e,t,r,s=0){try{const o=`${e}
|
|
342
|
+
|
|
343
|
+
${t}${r?`
|
|
344
|
+
|
|
345
|
+
Respond with valid JSON only.`:""}`;let a="claude";try{const{stdout:c}=await uc("which claude",{timeout:1e3});a=c.trim()}catch{const c=["/usr/local/bin/claude",`${process.env.HOME}/.nvm/versions/node/v20.16.0/bin/claude`,`${process.env.HOME}/.npm-global/bin/claude`];for(const u of c)try{await uc(`test -x "${u}"`,{timeout:1e3}),a=u;break}catch{}}const{stdout:i,stderr:l}=await new Promise((c,u)=>{var g,x,b;const h=kt(a,["-p",o,"--output-format","json","--max-turns","1"],{env:{...process.env}});(g=h.stdin)==null||g.end();let m="",f="";(x=h.stdout)==null||x.on("data",v=>{const N=v.toString();m+=N}),(b=h.stderr)==null||b.on("data",v=>{f+=v.toString()}),h.on("error",v=>{u(v)}),h.on("close",(v,N)=>{if(v===0)c({stdout:m,stderr:f});else{const w=new Error(`Command failed with exit code ${v}. stderr: ${f.substring(0,500)}`);w.code=v,w.stdout=m,w.stderr=f,u(w)}});const y=setTimeout(()=>{h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},5e3),u(new Error("Claude CLI command timed out after 60 seconds"))},6e4);h.on("close",()=>clearTimeout(y))});try{const c=JSON.parse(i);let u=c.result||c.response||c.text||c.content;if(!u)throw new Error("No response content from Claude CLI");const p=u.match(/^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/);if(p&&(u=p[1]),r){const h=Nv(u);if(h.valid)console.log("✅ Claude CLI: JSON validation passed");else{console.log(`⚠️ Claude CLI: Invalid JSON response (attempt ${s+1}/${pc+1})`),console.log(`⚠️ Claude CLI: JSON error: ${h.error}`),console.log(`⚠️ Claude CLI: Response length: ${u.length} bytes`);const m=Sv(u);if(console.log(`⚠️ Claude CLI: Appears truncated: ${m}`),m&&s<pc){console.log(`🔄 Claude CLI: Attempting to recover truncated JSON (retry ${s+1})`);const f=`The previous response was truncated and incomplete. Here's what was received:
|
|
346
|
+
|
|
347
|
+
\`\`\`json
|
|
348
|
+
${u}
|
|
349
|
+
\`\`\`
|
|
350
|
+
|
|
351
|
+
Please complete this JSON response. Make sure it's valid, complete JSON that properly closes all braces, brackets, and quotes. Return ONLY the complete, valid JSON.`;try{return await rp(e,f,r,s+1)}catch(y){console.log(`⚠️ Claude CLI: Recovery attempt failed: ${y}`)}}console.log(`⚠️ Claude CLI: Returning invalid JSON response after ${s+1} attempts`),console.log(`⚠️ Claude CLI: Downstream parsing will likely fail. First 500 chars: ${u.substring(0,500)}`)}}return u}catch(c){if(i.trim())return i.trim();throw new Error(`Failed to parse Claude CLI response: ${c}`)}}catch(o){const a=o.message;throw a.includes("command not found")||a.includes("ENOENT")?new Error("Claude Code CLI not found. Please ensure Claude Code is installed."):a.includes("not authenticated")||a.includes("subscription")?new Error("Claude Code CLI not authenticated. Please run `claude` to authenticate."):o}}const Cs=new $m({concurrency:100,timeout:1200*1e3,autoStart:!0}),hc={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},un={};async function za({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:o,model:a=tp,attempts:i=0}){var k,T,_,$,M,R,z;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Cv(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${Cs.size}, running=${Cs.pending}]`);const l=Date.now();let c,u=0;if(gv()){console.log("Using Claude CLI mode for AI request");const O=await rp(t,r,s);return{finishReason:"stop",completion:O,stats:{model:"claude-sonnet-4-5",prompt_type:e,system_message:t,prompt_text:r,response:O,input_tokens:0,output_tokens:0,cost:0}}}const p=Fo(a),h=process.env[p.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${p.provider.name}. Please set ${p.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${p.provider.name} for AI request`);const m=new Mm({apiKey:h,baseURL:p.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:a,responseType:o?"json_schema":s?"json_object":"text",jsonSchema:o},y=hv(f),g=await Cs.add(()=>(c=Date.now(),Dl(async()=>{const O=Date.now(),U=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],W=setInterval(()=>{const J=Math.floor((Date.now()-O)/1e3),j=Math.floor(J/10)%U.length;Ol(1,`${U[j]} [type=${e}, model=${a}, elapsed=${J}s]`)},1e4);try{return await m.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(W)}},{...hc,onFailedAttempt:O=>{u++,console.log(`CodeYam Error: Completion call failed [model=${a}]`,{error:O,prompt:r,systemMessage:t,attempts:i,retryCount:u})}})));if(!g)throw new Error("Completion call returned no result");const x=g,b=Date.now(),v=pv({chatRequest:f,chatCompletion:x,model:a});if(!v)throw new Error("Failed to get LLM call stats");v.retries=u,v.wait_ms=c-l,v.duration_ms=b-l;const N=(k=x.choices)==null?void 0:k[0];let w=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");w=(T=N.message)==null?void 0:T.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const S=s?C&&(((_=C.match(/\{[\s\S]*\}/))==null?void 0:_[0])??C):C;if(!S){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:S,rawCompletion:w,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await za({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:a,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(S.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(S)}catch(O){if(console.log("CodeYam Error: Invalid JSON in completion",{error:O.message,model:a,completion:S.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:O.message});const U=`Your previous response contained invalid JSON with the following error:
|
|
352
|
+
|
|
353
|
+
${O.message}
|
|
354
|
+
|
|
355
|
+
Here was your previous response:
|
|
356
|
+
\`\`\`
|
|
357
|
+
${S}
|
|
358
|
+
\`\`\`
|
|
359
|
+
|
|
360
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,W=await Cs.add(()=>Dl(async()=>{const L=Date.now(),E=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],F=setInterval(()=>{const I=Math.floor((Date.now()-L)/1e3),K=Math.floor(I/10)%E.length;Ol(1,`${E[K]} [type=${e}, model=${a}, elapsed=${I}s]`)},1e4);try{return await m.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:S},{role:"user",content:U}]},{timeout:300*1e3})}finally{clearInterval(F)}},{...hc,onFailedAttempt:L=>{console.log("CodeYam Error: Correction call failed",{error:L,attempts:i})}}));if(!W)throw new Error("Correction call returned no result");const J=W,j=(R=(M=($=J.choices)==null?void 0:$[0])==null?void 0:M.message)==null?void 0:R.content;let D=j;j&&(D=j.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const A=D&&(((z=D.match(/\{[\s\S]*\}/))==null?void 0:z[0])??D);if(!A)throw new Error("Correction attempt returned empty completion");try{JSON.parse(A),console.log("CodeYam: JSON correction successful");const L=Date.now();return v.duration_ms=L-l,{finishReason:J.choices[0].finish_reason,completion:A,stats:v}}catch(L){return console.log("CodeYam Error: Corrected JSON still invalid",{error:L.message,correctedCompletion:A.substring(0,500)}),await za({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:a,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${O.message}`)}return np(`completionCall_${e}`,{completion:S,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:S,stats:v}}async function Cv(e,t,r){var a,i,l,c,u;const s=await import("fs"),o=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.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 p=s.readdirSync(t).filter(v=>v.endsWith(".json"));if(p.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const v of p)try{const N=s.readFileSync(o.join(t,v),"utf-8"),w=JSON.parse(N);h[w.prompt_type]||(h[w.prompt_type]=[]),h[w.prompt_type].push(w)}catch(N){console.warn(`Failed to parse LLM fixture file ${v}:`,N)}for(const v of Object.keys(h))h[v].sort((N,w)=>{const C=N.created_at??0,S=w.created_at??0;return C-S});const m=h[e];if(!m||m.length===0){const v=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${v}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const v=r.match(/Scenario name must match exactly: "([^"]+)"/),N=v==null?void 0:v[1];if(N){const w={};for(const S of m)try{const T=((a=JSON.parse(S.props||"{}").scenario)==null?void 0:a.name)||"__NO_SCENARIO__";w[T]||(w[T]=[]),w[T].push(S)}catch{}const C=w[N];if(C&&C.length>0){const S=`${t}::${e}::${N}`;un[S]===void 0&&(un[S]=0);const k=un[S];un[S]=(k+1)%C.length,f=C[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${k+1}/${C.length}]`)}else{const S=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${S}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const v=`${t}::${e}`;un[v]===void 0&&(un[v]=0);const N=un[v];un[v]=(N+1)%m.length,f=m[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+1}/${m.length}]`)}let g;try{g=((c=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:c.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((u=x.match(/\{[\s\S]*\}/))==null?void 0:u[0])??x);return np(`completionCall_${e}`,{completion:b||"",finishReason:"stop"}),{finishReason:"stop",completion:b||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(p){throw console.error("CodeYam Test Error: Failed to replay LLM call:",p),p}}function mc(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function kv(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),o=Xa(),a=Date.now(),i={...r,id:o,created_at:a,props:s};let l;const c=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?l=G.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=G.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const p=G.dirname(l);return await Pe.mkdir(p,{recursive:!0}),await Pe.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:o}}catch(p){return console.log("CodeYam Error: Failed to save LLM call to local file",p),{id:"-1"}}const u=mc();if(!u)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[p,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${o} property ${p} with explicit value 'undefined'`);try{return await new co().send(new Fm({TableName:mc(),Item:Dm(i,{removeUndefinedValues:!0})})),{id:o}}catch(p){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${u}`,p),{id:"-1"}}}new co({});new co({});new co({});const Ev=3,_v=2,Ii=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Ev*String(t).length*(1+_v)});new si(Ii());new si(Ii());new si(Ii());class jv{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class Pv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Av{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Tv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Mv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class $v{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];if(s.addType(a,"function"),s.addEquivalence(a.withParameter(1),r.withElement("*")),o.args.length>1){const i=o.args[1];s.addEquivalence(a.withParameter(0),i)}}}isComplete(){return!0}}class Fv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const o=t.getLastFunctionCallSegment();o&&o.args.forEach(a=>{s.addEquivalence(t,a)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Rv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const o=t.withReturnValues();s.addType(o,"unknown")}isComplete(){return!0}}class Dv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let a=2;a<o.args.length;a++){const i=o.args[a];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Iv{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let a=0;a<o.args.length;a++)s.addEquivalence(r.withElement("*"),t.withParameter(a))}isComplete(){return!0}}class Ov{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addEquivalence(t.withParameter(0),a)}}isComplete(){return!0}}class Lv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class zv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Bv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Yv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Uv{getReturnType(){return"object"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"array")}}isComplete(){return!0}}class Wv{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Jv{getReturnType(){return"unknown"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),a.withProperty("returnValue"))}}isComplete(){return!0}}class Hv{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Vv{getReturnType(){return"array"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),o&&o.args.length>0){const a=o.args[0];s.addEquivalence(t.withParameter(0),a)}}isComplete(){return!0}}class Kv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}class Gv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}function qv(){const e=new jv;return e.register("filter",new Pv,"Array"),e.register("map",new Lv,"Array"),e.register("flatMap",new zv,"Array"),e.register("join",new Ov,"Array"),e.register("find",new Mv,"Array"),e.register("findLast",new Yv,"Array"),e.register("at",new Bv,"Array"),e.register("reduce",new $v,"Array"),e.register("concat",new Fv,"Array"),e.register("slice",new Rv,"Array"),e.register("splice",new Dv,"Array"),e.register("push",new Iv,"Array"),e.register("some",new Av,"Array"),e.register("every",new Tv,"Array"),e.register("fromEntries",new Uv,"Object"),e.register("split",new Wv,"String"),e.register("then",new Jv,"Promise"),e.register("useState",new Vv,"React"),e.register("useMemo",new Hv,"React"),e.register("has",new Kv),e.register("delete",new Gv),e}qv();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 Qv=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Zv=new Set(["find","findLast","at","pop","shift"]),Xv=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),ew=new Set([...Qv,...Zv,...Xv]),tw=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),nw=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),rw=new Set([...tw,...nw]);[...ew,...rw];class sw{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const o=" ".repeat(this.depth),a=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${a}${o}${r}`,JSON.stringify(s)):console.info(`${a}${o}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new sw({enabled:!1});function jn(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),o=new Set(Object.keys(t??{}));for(const a of o)s.has(a)||(r.added[a]=t[a]);for(const a of s)o.has(a)||(r.removed[a]=e[a]);for(const a of s)o.has(a)&&e[a]!==t[a]&&(r.changed[a]={from:e[a],to:t[a]});return r}function ow(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function ks(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let aw=0;class Oi{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++aw,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,s){var c,u,p,h;if(!this.isEnabled())return;const o=this.traces.get(t);if(!o)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const a=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:a},l=o.stages[o.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:jn(l.data.signatureSchema,a.signatureSchema),returnValueSchema:jn(l.data.returnValueSchema,a.returnValueSchema)},a.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const m=new Set([...Object.keys(a.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of m){const y=(c=l.data.dependencySchemas)==null?void 0:c[f],g=(u=a.dependencySchemas)==null?void 0:u[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const b=`${f}::${x}`,v=(p=y==null?void 0:y[x])==null?void 0:p.returnValueSchema,N=(h=g==null?void 0:g[x])==null?void 0:h.returnValueSchema,w=jn(v,N);ow(w)&&(i.diffFromPrevious.dependencySchemas[b]=w)}}}o.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var o;const t={},r=new Map;for(const[a,i]of this.traces){let l=0;for(const c of i.stages){if(!c.diffFromPrevious)continue;const p=`${((o=i.stages[i.stages.indexOf(c)-1])==null?void 0:o.stage)??"start"}→${c.stage}`;if(t[p]||(t[p]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const h=c.diffFromPrevious.signatureSchema;t[p].added+=Object.keys(h.added).length,t[p].removed+=Object.keys(h.removed).length,t[p].changed+=Object.keys(h.changed).length,l+=ks(h)}if(c.diffFromPrevious.returnValueSchema){const h=c.diffFromPrevious.returnValueSchema;t[p].added+=Object.keys(h.added).length,t[p].removed+=Object.keys(h.removed).length,t[p].changed+=Object.keys(h.changed).length,l+=ks(h)}}r.set(a,l)}const s=[...r.entries()].sort((a,i)=>i[1]-a[1]).slice(0,10).map(([a])=>a);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){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(u=>`${u}(${this.traces.get(u).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:o}=this.computeFlushSummary(),a={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:o},l=G.dirname(this.outputPath);q.existsSync(l)||q.mkdirSync(l,{recursive:!0});const c=q.openSync(this.outputPath,"w");try{q.writeSync(c,`{
|
|
361
|
+
"meta": `),q.writeSync(c,JSON.stringify(a,null,2)),q.writeSync(c,`,
|
|
362
|
+
"summary": `),q.writeSync(c,JSON.stringify(i,null,2)),q.writeSync(c,`,
|
|
363
|
+
"entities": {`);let u=!0;for(const[p,h]of this.traces)u||q.writeSync(c,","),q.writeSync(c,`
|
|
364
|
+
${JSON.stringify(p)}: `),q.writeSync(c,JSON.stringify(h,null,2)),u=!1;q.writeSync(c,`
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{q.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=q.readFileSync(t,"utf-8"),s=JSON.parse(r),o=new Oi({enabled:!1});o.projectSlug=s.meta.projectSlug;for(const[a,i]of Object.entries(s.entities))o.traces.set(a,i);return o}getSummary(){var o,a,i;const t={},r=new Map;for(const[l,c]of this.traces){let u=0;for(let p=1;p<c.stages.length;p++){const h=c.stages[p],f=`${((o=c.stages[p-1])==null?void 0:o.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(a=h.diffFromPrevious)!=null&&a.signatureSchema){const y=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,u+=ks(y)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const y=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,u+=ks(y)}}r.set(l,u)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(o=>o.path&&r.test(o.path)):s.operations:[]}tracePath(t,r){var a,i;const s=this.traces.get(t),o=[];if(!s)return{entityName:t,path:r,history:o};for(const l of s.stages){const c=(a=l.data.signatureSchema)==null?void 0:a[r],u=(i=l.data.returnValueSchema)==null?void 0:i[r],p=c??u;p!==void 0&&o.push({stage:l.stage,value:p})}for(const l of s.operations)l.path===r&&o.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:o}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const o=[],a=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,c]of Object.entries(i.data.signatureSchema??{}))a.test(l)&&o.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))a.test(l)&&o.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[u,p]of Object.entries(c))for(const[h,m]of Object.entries(p.returnValueSchema??{}))a.test(h)&&o.push({stage:i.stage,path:`${l}/${u}::${h}`,type:m,schemaType:"dependency"})}return o}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const o=new Set(["length","toString","valueOf","constructor"]),a=new Map,i=(c,u)=>{const p=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!p)return;const h=p[1],m=p[2]==="[]";if(o.has(h))return;const f=h+(m?"[]":"");a.has(f)||a.set(f,[]),a.get(f).push({path:c,type:u})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,u]of Object.entries(c))for(const[p,h]of Object.entries(u.returnValueSchema??{}))i(p,h);const l=[];for(const[c,u]of a)new Set(u.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:u.map(h=>({...h,stage:s.stage}))});return l.sort((c,u)=>{const p=new Set(c.paths.map(m=>m.type)).size;return new Set(u.paths.map(m=>m.type)).size-p}),l}getStageDiffSummary(t,r,s){const o=this.traces.get(t);if(!o)return null;const a=o.stages.find(m=>m.stage===r),i=o.stages.find(m=>m.stage===s);if(!a||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=a.data.returnValueSchema??{},u=i.data.returnValueSchema??{},p=new Set(Object.keys(c)),h=new Set(Object.keys(u));for(const m of h)p.has(m)?c[m]!==u[m]&&l.typeChanged.push({path:m,from:c[m],to:u[m]}):l.added.push(`${m}: ${u[m]}`);for(const m of p)h.has(m)||l.removed.push(`${m}: ${c[m]}`);return l}traceSchemaTransform(t,r,s,o,a){if(!this.enabled)return o(s),s;const i={...s};o(s);const l=jn(i,s);for(const[c,u]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:u,context:{...a,changeType:"added"}});for(const[c,u]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:u,after:void 0,context:{...a,changeType:"removed"}});for(const[c,{from:u,to:p}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:u,after:p,context:{...a,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,o,a){if(!this.enabled)return;const i=jn(s,o);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...a,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...a,changeType:"removed"}});for(const[l,{from:c,to:u}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:u,context:{...a,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,o,a="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const c=s[i][l];(a==="signature"||a==="both")&&c.signatureSchema&&o(c.signatureSchema),(a==="returnValue"||a==="both")&&c.returnValueSchema&&o(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],u={filePath:i,dependencyName:l};(a==="signature"||a==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,o,{...u,schemaType:"signature"}),(a==="returnValue"||a==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,o,{...u,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,o){var i;if(!this.enabled){o();return}const a={};for(const l in s){a[l]={};for(const c in s[l]){const u=s[l][c];a[l][c]={sig:{...u.signatureSchema||{}},rv:{...u.returnValueSchema||{}}}}}o();for(const l in s)for(const c in s[l]){const u=s[l][c],p=(i=a[l])==null?void 0:i[c],h={filePath:l,dependencyName:c};if(u.signatureSchema){const m=(p==null?void 0:p.sig)||{},f=jn(m,u.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(u.returnValueSchema){const m=(p==null?void 0:p.rv)||{},f=jn(m,u.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function iw(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const fc=new Oi({enabled:iw(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{fc.isEnabled()&&fc.flush()});function sp(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 Rm.parse(e)}catch(r){const o=r.message.match(/invalid character .* at (\d+):(\d+)/);if(o){const a=parseInt(o[2],10);if(e.substring(a-2,a-1)==='"')return e=e.substring(0,a-2)+"\\"+e.substring(a-2),sp(e)}return null}}function lw({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let o="";return s&&s.length>0&&(o=`
|
|
368
|
+
User-selected Execution Flow Values:
|
|
369
|
+
The user has specifically requested these values be used in the scenario:
|
|
370
|
+
${s.map(a=>` - ${a.path}: ${a.value}${a.isCustom?" (custom value)":""}`).join(`
|
|
371
|
+
`)}
|
|
372
|
+
|
|
373
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
374
|
+
`),`Mock Scenario Data Structure:
|
|
375
|
+
\`\`\`
|
|
376
|
+
${JSON.stringify(r,null,2)}
|
|
377
|
+
\`\`\`
|
|
378
|
+
Existing Mock Scenario Data:
|
|
379
|
+
\`\`\`
|
|
380
|
+
${JSON.stringify(t,null,2)}
|
|
381
|
+
\`\`\`
|
|
382
|
+
${o}
|
|
383
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
384
|
+
`}function cw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o}){const a=s.find(i=>i.name===ho);return`Mock Scenario Data Structure:
|
|
385
|
+
\`\`\`
|
|
386
|
+
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
387
|
+
\`\`\`
|
|
388
|
+
|
|
389
|
+
Existing Mock Scenario Data:
|
|
390
|
+
\`\`\`
|
|
391
|
+
${JSON.stringify(s.map(i=>({name:i.name,data:Dr(a.metadata.data,i.metadata.data)})),null,2)}
|
|
392
|
+
\`\`\`
|
|
393
|
+
|
|
394
|
+
Mock Scenario that should be edited: "${t}"
|
|
395
|
+
${r?`The portion of the data that should be edited:
|
|
396
|
+
\`\`\`
|
|
397
|
+
${JSON.stringify(r,null,2)}
|
|
398
|
+
\`\`\``:""}
|
|
399
|
+
|
|
400
|
+
How this data should be changed: "${e}"
|
|
401
|
+
`}async function dw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o,flowSelections:a,model:i}){const l=t?cw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o}):lw({description:e,existingScenarios:s,scenariosDataStructure:o,flowSelections:a}),c=await za({type:"guessScenarioDataFromDescription",systemMessage:t?pw(r):uw,prompt:l,model:i??av});await kv({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o,model:i},...c.stats});const{completion:u}=c;return u?sp(u):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const uw=`
|
|
402
|
+
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.
|
|
403
|
+
|
|
404
|
+
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.
|
|
405
|
+
|
|
406
|
+
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.
|
|
407
|
+
|
|
408
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
409
|
+
\`\`\`
|
|
410
|
+
export type ScenarioData = {
|
|
411
|
+
name: string;
|
|
412
|
+
description: string;
|
|
413
|
+
data: {
|
|
414
|
+
mockData: { [key: string]: unknown };
|
|
415
|
+
argumentsData: { [key: string]: unknown };
|
|
416
|
+
};
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
\`\`\`
|
|
420
|
+
`,pw=e=>`
|
|
421
|
+
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.
|
|
422
|
+
|
|
423
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
424
|
+
${e?`
|
|
425
|
+
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.`:""}
|
|
426
|
+
|
|
427
|
+
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.
|
|
428
|
+
|
|
429
|
+
You must respond with valid JSON following this type definition:
|
|
430
|
+
\`\`\`
|
|
431
|
+
{
|
|
432
|
+
data: {
|
|
433
|
+
mockData: { [key: string]: unknown };
|
|
434
|
+
argumentsData: { [key: string]: unknown };
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
\`\`\`
|
|
438
|
+
`;async function hw({request:e}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:o,editingMockName:a,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return le({error:"Missing required field: description or flowSelections"},{status:400});const c=await dw({description:r||"",existingScenarios:s??[],scenariosDataStructure:o,editingMockName:a,editingMockData:i,flowSelections:l}),u=(c==null?void 0:c.data)||c;return le({success:!0,data:u})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),le({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const mw=Object.freeze(Object.defineProperty({__proto__:null,action:hw},Symbol.toStringTag,{value:"Module"}));function Pn(e,t){for(const r of[".env.local",".env",".env.development.local",".env.development"])try{const s=ee.join(e,r);if(!de.existsSync(s))continue;const o=de.readFileSync(s,"utf-8");for(const a of o.split(`
|
|
439
|
+
`)){const i=a.trim();if(!i||i.startsWith("#"))continue;const l=i.indexOf("=");if(l===-1)continue;const c=i.slice(0,l).trim();let u=i.slice(l+1).trim();if((u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),c===t&&u)return u}}catch{}return null}function fw(e,t,r){const s=ee.join(e,".env.local");let o=[];try{o=de.readFileSync(s,"utf-8").split(`
|
|
440
|
+
`)}catch{}const a=o.findIndex(l=>{const c=l.trim();if(c.startsWith("#"))return!1;const u=c.indexOf("=");return u===-1?!1:c.slice(0,u).trim()===t}),i=`${t}=${r}`;a>=0?o[a]=i:(o.length>0&&o[o.length-1].trim()!==""&&o.push(""),o.push(i)),de.writeFileSync(s,o.join(`
|
|
441
|
+
`))}function gw(e){const t=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(t)return{owner:t[1],repo:t[2]};const r=e.match(/github\.com\/([^/]+)\/([^/.]+)/);return r?{owner:r[1],repo:r[2]}:null}const yw="https://api.vercel.com";async function it(e,t,r){try{const s=await fetch(`${yw}${e}`,{method:(r==null?void 0:r.method)||"GET",headers:{Authorization:`Bearer ${t}`,...r!=null&&r.body?{"Content-Type":"application/json"}:{}},...r!=null&&r.body?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(15e3)}),o=await s.json();return{ok:s.ok,status:s.status,data:o}}catch(s){return{ok:!1,status:0,data:{error:s instanceof Error?s.message:String(s)}}}}function gc(e){try{const t=Me("git remote get-url origin",{cwd:e,encoding:"utf8"}).trim();return gw(t)}catch{return null}}async function xw({request:e}){var t,r,s,o,a,i,l,c,u,p,h,m,f,y,g,x,b,v,N,w,C,S,k,T,_,$,M,R,z,O,U,W,J,j;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const D=Ce()||process.cwd(),A=await e.json(),L=A.action;if(L==="check-token"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,hasToken:!1,error:"VERCEL_TOKEN not found in .env.local"});const F=await it("/v2/user",E);return F.ok?Response.json({ok:!0,hasToken:!0,user:{username:((s=F.data.user)==null?void 0:s.username)||((o=F.data.user)==null?void 0:o.name),email:(a=F.data.user)==null?void 0:a.email}}):Response.json({ok:!1,hasToken:!0,error:`Token invalid (${F.status}): ${((r=(t=F.data)==null?void 0:t.error)==null?void 0:r.message)||"unknown error"}`})}if(L==="save-token"){const E=A.token;if(!E||typeof E!="string")return Response.json({ok:!1,error:"Token is required"});fw(D,"VERCEL_TOKEN",E);const F=await it("/v2/user",E);return F.ok?Response.json({ok:!0,saved:!0,user:{username:((i=F.data.user)==null?void 0:i.username)||((l=F.data.user)==null?void 0:l.name),email:(c=F.data.user)==null?void 0:c.email}}):Response.json({ok:!1,saved:!0,error:`Token saved but verification failed (${F.status})`})}if(L==="list-projects"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const F=await it("/v9/projects?limit=20",E);if(!F.ok)return Response.json({ok:!1,error:"Failed to list projects"});const I=(F.data.projects||[]).map(V=>({id:V.id,name:V.name,framework:V.framework}));let K=null;const Q=gc(D);if(Q){const V=I.find(Y=>Y.name.toLowerCase()===Q.repo.toLowerCase());V&&(K=V.id)}return Response.json({ok:!0,projects:I,suggestedProjectId:K,gitHubRepo:Q?`${Q.owner}/${Q.repo}`:null})}if(L==="create-project"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const F=gc(D);if(!F)return Response.json({ok:!1,error:"Could not detect a GitHub remote. Push your code to GitHub first, then try again."});const I=ee.join(D,".codeyam","config.json"),K=F.repo;let Q=null;try{((p=(u=JSON.parse(de.readFileSync(I,"utf8")).webapps)==null?void 0:u[0])==null?void 0:p.framework)==="Next"&&(Q="nextjs")}catch{}const V={name:A.projectName||K,framework:Q,gitRepository:{type:"github",repo:`${F.owner}/${F.repo}`}},Y=await it("/v10/projects",E,{method:"POST",body:V});if(!Y.ok){const H=((m=(h=Y.data)==null?void 0:h.error)==null?void 0:m.message)||((y=(f=Y.data)==null?void 0:f.error)==null?void 0:y.code)||"Failed to create project";return Response.json({ok:!1,error:H})}const B=Y.data;try{const H=JSON.parse(de.readFileSync(I,"utf8"));H.hosting={...H.hosting,provider:"vercel",vercelProjectId:B.id,vercelProjectName:B.name},de.writeFileSync(I,JSON.stringify(H,null,2))}catch{}return Response.json({ok:!0,project:{id:B.id,name:B.name,framework:B.framework}})}if(L==="link-project"){const{projectId:E,projectName:F}=A;if(!E)return Response.json({ok:!1,error:"projectId is required"});const I=ee.join(D,".codeyam","config.json"),K=JSON.parse(de.readFileSync(I,"utf8"));return K.hosting={...K.hosting,provider:"vercel",vercelProjectId:E,vercelProjectName:F||null},de.writeFileSync(I,JSON.stringify(K,null,2)),Response.json({ok:!0})}if(L==="check-env-vars"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const F=ee.join(D,".codeyam","config.json"),I=JSON.parse(de.readFileSync(F,"utf8")),K=(g=I.hosting)==null?void 0:g.vercelProjectId;if(!K)return Response.json({ok:!1,error:"No Vercel project linked"});const Q=await it(`/v9/projects/${K}/env`,E);if(!Q.ok)return Response.json({ok:!1,error:"Failed to fetch Vercel env vars"});const V=new Set((Q.data.envs||[]).map(oe=>oe.key)),Y=I.techStack||{},B=[];for(const oe of["databases","services","infrastructure"]){const Z=Y[oe];if(Array.isArray(Z)){for(const re of Z)if(re.envKeys&&Array.isArray(re.envKeys))for(const ue of re.envKeys)B.push({key:ue,service:re.name})}}const H=B.map(({key:oe,service:Z})=>({key:oe,service:Z,configuredOnVercel:V.has(oe)})),ne=B.length===0||H.every(oe=>oe.configuredOnVercel);return Response.json({ok:!0,allConfigured:ne,envVars:H,vercelEnvCount:V.size})}if(L==="full-status"){const E=Pn(D,"VERCEL_TOKEN"),F=ee.join(D,".codeyam","config.json");let I={};try{I=JSON.parse(de.readFileSync(F,"utf8"))}catch{}const K={hasToken:!!E,tokenVerified:!1,user:null,projectLinked:!!((x=I.hosting)!=null&&x.vercelProjectId),projectName:((b=I.hosting)==null?void 0:b.vercelProjectName)||null,dashboardUrl:null,productionUrl:null,envVarsChecked:!1,envVars:[]};if(E){const Q=await it("/v2/user",E);if(Q.ok&&(K.tokenVerified=!0,K.user={username:((v=Q.data.user)==null?void 0:v.username)||((N=Q.data.user)==null?void 0:N.name),email:(w=Q.data.user)==null?void 0:w.email}),K.projectLinked){const V=await it(`/v9/projects/${I.hosting.vercelProjectId}`,E);if(V.ok){const H=V.data;let ne=null;if(H.accountId){const Z=await it(`/v2/teams/${H.accountId}`,E);Z.ok&&(ne=Z.data.slug)}K.dashboardUrl=ne?`https://vercel.com/${ne}/${H.name}`:`https://vercel.com/~/project/${H.name}`;const oe=((S=(C=H.targets)==null?void 0:C.production)==null?void 0:S.alias)||H.alias||[];if(oe.length>0){const Z=oe.find(re=>!re.endsWith(".vercel.app"));K.productionUrl=`https://${Z||oe[0]}`}else H.name&&(K.productionUrl=`https://${H.name}.vercel.app`)}const Y=await it(`/v6/deployments?projectId=${I.hosting.vercelProjectId}&limit=1&target=production`,E);if(Y.ok){const H=Y.data.deployments||[];if(H.length>0){const ne=H[0],oe=((k=ne.meta)==null?void 0:k.githubCommitSha)||((T=ne.meta)==null?void 0:T.gitlabCommitSha)||((_=ne.gitSource)==null?void 0:_.sha)||null;let Z=0;if(oe)try{const re=Me(`git rev-list --count ${oe}..HEAD`,{cwd:D,encoding:"utf8"}).trim();Z=parseInt(re,10)||0}catch{}K.lastDeployment={state:ne.state||ne.readyState,url:ne.url?`https://${ne.url}`:null,createdAt:ne.createdAt,commitsSince:Z}}else K.lastDeployment=null}const B=await it(`/v9/projects/${I.hosting.vercelProjectId}/env`,E);if(B.ok){const H=new Set((B.data.envs||[]).map(Z=>Z.key)),ne=I.techStack||{},oe=[];for(const Z of["databases","services","infrastructure"]){const re=ne[Z];if(Array.isArray(re)){for(const ue of re)if(ue.envKeys&&Array.isArray(ue.envKeys))for(const we of ue.envKeys)oe.push({key:we,service:ue.name})}}K.envVarsChecked=!0,K.envVars=oe.map(({key:Z,service:re})=>({key:Z,service:re,configuredOnVercel:H.has(Z)}))}}}return Response.json({ok:!0,...K})}if(L==="deploy"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const F=ee.join(D,".codeyam","config.json"),I=JSON.parse(de.readFileSync(F,"utf8")),K=($=I.hosting)==null?void 0:$.vercelProjectName;if(!K)return Response.json({ok:!1,error:"No Vercel project linked"});const Q=(M=I.hosting)==null?void 0:M.vercelProjectId,V=await it(`/v9/projects/${Q}`,E);if(!V.ok)return Response.json({ok:!1,error:"Failed to fetch project details"});const Y=V.data,B=(R=Y.link)==null?void 0:R.repoId;if(!B)return Response.json({ok:!1,error:"Project is not linked to a GitHub repository on Vercel"});let H="main";try{H=Me("git rev-parse --abbrev-ref HEAD",{cwd:D,encoding:"utf8"}).trim()}catch{}let ne;try{ne=Me("git rev-parse HEAD",{cwd:D,encoding:"utf8"}).trim()}catch{}const oe=await it("/v13/deployments",E,{method:"POST",body:{name:K,target:"production",gitSource:{type:Y.link.type||"github",repoId:B,ref:H,...ne?{sha:ne}:{}}}});if(!oe.ok){const Z=((O=(z=oe.data)==null?void 0:z.error)==null?void 0:O.message)||((W=(U=oe.data)==null?void 0:U.error)==null?void 0:W.code)||"Failed to trigger deployment";return Response.json({ok:!1,error:Z})}return Response.json({ok:!0,deployment:{id:oe.data.id,url:oe.data.url?`https://${oe.data.url}`:null,state:oe.data.readyState||oe.data.state}})}if(L==="check-deployment"){const E=Pn(D,"VERCEL_TOKEN");if(!E)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const F=A.deploymentId;if(!F)return Response.json({ok:!1,error:"deploymentId is required"});const I=await it(`/v13/deployments/${F}`,E);if(!I.ok)return Response.json({ok:!1,error:"Failed to check deployment status"});const K=I.data,Q=K.readyState||K.state||"UNKNOWN";let V=null;if(Q==="ERROR"||Q==="CANCELED"){const H=await it(`/v2/deployments/${F}/events?limit=20&direction=backward`,E);if(H.ok){const oe=(H.data||[]).filter(Z=>Z.type==="error"||Z.type==="stderr");oe.length>0&&(V=oe.map(Z=>{var re;return((re=Z.payload)==null?void 0:re.text)||Z.text||""}).filter(Boolean).slice(0,5).join(`
|
|
442
|
+
`))}V||(V=K.errorMessage||((J=K.error)==null?void 0:J.message)||"Build failed")}const Y=ee.join(D,".codeyam","config.json");let B=null;try{const H=JSON.parse(de.readFileSync(Y,"utf8"));if((j=H.hosting)!=null&&j.vercelProjectId){const ne=await it(`/v9/projects/${H.hosting.vercelProjectId}`,E);if(ne.ok&&ne.data.accountId){const oe=await it(`/v2/teams/${ne.data.accountId}`,E);oe.ok&&(B=`https://vercel.com/${oe.data.slug}/${H.hosting.vercelProjectName}/${F.replace("dpl_","")}`)}}}catch{}return Response.json({ok:!0,state:Q,url:K.url?`https://${K.url}`:null,errorMessage:V,logsUrl:B})}return Response.json({ok:!1,error:`Unknown action: ${L}`})}catch(D){const A=D instanceof Error?D.message:String(D);return Response.json({ok:!1,error:A},{status:500})}}const bw=Object.freeze(Object.defineProperty({__proto__:null,action:xw},Symbol.toStringTag,{value:"Module"}));function vw(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],o=new Date(r);o.setDate(o.getDate()-s);const a=o.toISOString().split("T")[0],i=e.filter(h=>h.date>=a),l=new Set(i.map(h=>h.commitSha).filter(Boolean)),c=new Map;for(const h of i)if(h.scenarioScreenshots)for(const m of h.scenarioScreenshots){c.has(m.name)||c.set(m.name,[]);const f=c.get(m.name);f.some(y=>y.path===m.path)||f.push({path:m.path,time:h.time})}for(const h of c.values())h.sort((m,f)=>m.time.localeCompare(f.time));const u=[],p=new Map;for(const[h,m]of c){const f=h.indexOf(" - ");if(f!==-1){const y=h.slice(0,f);p.has(y)||p.set(y,[]),p.get(y).push({name:h,screenshots:m})}else u.push({name:h,screenshots:m})}return{commitCount:l.size,entryCount:i.length,appScenarios:u,componentGroups:p,totalScenarios:c.size}}function ww(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function Nw(e){const t=new Map;for(const r of e){let s;if("componentName"in r&&r.componentName)s=r.componentName;else if("componentName"in r&&r.componentName===null)s="App";else{const a=r.name.indexOf(" - ");s=a!==-1?r.name.slice(0,a):"App"}const o=t.get(s)||[];o.push(r),t.set(s,o)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function Sw(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function Cw(e){const{title:t,timeStr:r,type:s,description:o,allScenarioNames:a,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:u,featureName:p,userPrompt:h}=e,m=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(p&&m.push(`**Feature:** ${p}`),h&&m.push(`**Prompt:** ${h}`),a.length>0&&m.push(`**Scenarios:** ${a.join(", ")}`),m.push(""),m.push(o),i&&(m.push(""),m.push(``)),l.length>0){m.push(""),m.push("**Scenario Screenshots:**");for(const f of l)m.push(""),m.push(``)}return c&&u&&(m.push(""),m.push(`**Commit:** \`${c}\` — ${u}`)),m.push(""),m.join(`
|
|
443
|
+
`)}function kw(e,t){return e.findIndex(r=>r.time===t)}function Ew(e){return!!e.commitSha}function _w(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function jw(e,t,r,s){const o=`
|
|
444
|
+
**Commit:** \`${r}\` — ${s||"no message"}
|
|
445
|
+
`,a=`### ${t}`,i=e.lastIndexOf(a);if(i===-1)return null;const l=e.indexOf(`
|
|
446
|
+
---
|
|
447
|
+
`,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+o+e.slice(c)}async function Pw(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await De(t),o=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${o.length} matching scenarios:`,o.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const a=o.filter(c=>!c.screenshot_path);a.length>0&&console.warn(`[editorScenarioLookup] ${a.length} scenarios have no screenshot_path:`,a.map(c=>c.name));const i=o.filter(c=>c.screenshot_path),l=Tt(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,pageFilePath:c.page_file_path||null,url:c.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function Aw(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Ye();if(!t)return[];const{project:r}=await De(t),o=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),a=new Set(e),l=o.filter(u=>{const p=tn({componentName:u.component_name,pageFilePath:u.page_file_path,url:u.url});return a.has(p)}).filter(u=>u.screenshot_path),c=Tt(l,u=>u.name).map(u=>({name:u.name,screenshotPath:u.screenshot_path,scenarioId:u.id,componentName:u.component_name||null,pageFilePath:u.page_file_path||null,url:u.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function op(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await De(t),s=$e(),o=Ce()||process.cwd();let a=null;const i=G.join(o,".codeyam","editor-step.json");try{const m=q.readFileSync(i,"utf8");a=JSON.parse(m).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!a)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>a?e:a,c=Xr(l),u=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${u.length} scenarios since ${l}`);const p=u.filter(m=>m.screenshot_path),h=Tt(p,m=>m.name).map(m=>({name:m.name,screenshotPath:m.screenshot_path,scenarioId:m.id,componentName:m.component_name||null,pageFilePath:m.page_file_path||null,url:m.url||null}));return console.log(`[editorScenarioLookup] Found ${h.length} session scenarios with screenshots`),h}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function Ba(e,t,r){const s=G.join(t,".codeyam","journal","screenshots");await Pe.mkdir(s,{recursive:!0});const o=[];for(const a of e){const i=G.join(t,".codeyam","editor-scenarios",a.screenshotPath),l=Sw(a.name,r),c=G.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${a.name}" from ${i} → ${c}`);try{await Pe.access(i),await Pe.copyFile(i,c),o.push({name:a.name,path:`screenshots/${l}`,componentName:a.componentName,url:a.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${a.name}"`)}catch(u){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,u instanceof Error?u.message:u)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${o.length} scenarios have screenshots embedded`),o}async function Tw({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:o,description:a,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=G.join(l,".codeyam","journal"),u=G.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let p={entries:[]};try{const g=await Pe.readFile(u,"utf8");p=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const h=kw(p.entries,r);if(h===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const m=p.entries[h];if(Ew(m))return console.log(`[editor-journal-update] Rejected: entry "${m.title}" already committed (${m.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${m.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await op();g.length>0&&(f=g.map(x=>x.name),y=await Ba(g,l,new Date))}if(_w(m,{commitSha:s,commitMessage:o,description:a,scenarios:f,scenarioScreenshots:y}),p.entries[h]=m,await Pe.writeFile(u,JSON.stringify(p,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=m.date,x=G.join(c,`${g}.md`);let b="";try{b=await Pe.readFile(x,"utf8")}catch{}if(b){const v=jw(b,m.title,s,o||null);v&&(await Pe.writeFile(x,v,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return Nt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${m.title}"`),new Response(JSON.stringify({success:!0,entry:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Mw=Object.freeze(Object.defineProperty({__proto__:null,action:Tw},Symbol.toStringTag,{value:"Module"}));async function $w({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await Wu(r);let o=0;const a={};for(const[c,u]of Object.entries(s))u.errors.length>0&&(a[c]=u,o+=u.errors.length);let i=ec();if(!i)for(let c=0;c<20&&(await new Promise(u=>setTimeout(u,500)),i=ec(),!i);c++);const l=((t=i==null?void 0:i.errors)==null?void 0:t.length)??0;return new Response(JSON.stringify({hasErrors:o>0||l>0,totalErrors:o+l,scenarios:a,livePreview:i?{loaded:i.loaded,hasContent:i.hasContent,errors:i.errors,url:i.url,lastUpdated:i.lastUpdated}:null}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-client-errors] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const Fw=Object.freeze(Object.defineProperty({__proto__:null,loader:$w},Symbol.toStringTag,{value:"Module"}));async function Rw({request:e}){try{const r=(await zn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],c=l.scenarios||[],u=!((y=l.status)!=null&&y.finishedAt),p=i.entityType||"visual",m=p==="library"||p==="functionCall"?c.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):c.some(g=>{var x,b,v,N;return((b=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:b[0])&&!((v=g.metadata)!=null&&v.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=c.length;return{name:i.name,entityType:p,filePath:i.filePath||"",hasScreenshot:m,isAnalyzing:u,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),o=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),a=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:o,analyzing:a}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Dw=Object.freeze(Object.defineProperty({__proto__:null,loader:Rw},Symbol.toStringTag,{value:"Module"})),Iw="https://api.github.com";function ap(e,t){for(const r of[".env.local",".env",".env.development.local",".env.development"])try{const s=ee.join(e,r);if(!de.existsSync(s))continue;const o=de.readFileSync(s,"utf-8");for(const a of o.split(`
|
|
448
|
+
`)){const i=a.trim();if(!i||i.startsWith("#"))continue;const l=i.indexOf("=");if(l===-1)continue;const c=i.slice(0,l).trim();let u=i.slice(l+1).trim();if((u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),c===t&&u)return u}}catch{}return null}function Ow(e,t,r){const s=ee.join(e,".env.local");let o=[];try{o=de.readFileSync(s,"utf-8").split(`
|
|
449
|
+
`)}catch{}const a=o.findIndex(l=>{const c=l.trim();if(c.startsWith("#"))return!1;const u=c.indexOf("=");return u===-1?!1:c.slice(0,u).trim()===t}),i=`${t}=${r}`;a>=0?o[a]=i:(o.length>0&&o[o.length-1].trim()!==""&&o.push(""),o.push(i)),de.writeFileSync(s,o.join(`
|
|
450
|
+
`))}function Ze(e,t){try{return{ok:!0,stdout:Me(e,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),stderr:""}}catch(r){return{ok:!1,stdout:(r.stdout||"").trim(),stderr:(r.stderr||"").trim()}}}async function Es(e,t,r){try{const s=await fetch(`${Iw}${e}`,{method:(r==null?void 0:r.method)||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json",...r!=null&&r.body?{"Content-Type":"application/json"}:{}},...r!=null&&r.body?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(15e3)}),o=await s.json();return{ok:s.ok,status:s.status,data:o}}catch(s){return{ok:!1,status:0,data:{error:s instanceof Error?s.message:String(s)}}}}function Lw(e){const t=Ze("git remote get-url origin",e);if(!t.ok)return null;const r=t.stdout,s=r.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(s)return{owner:s[1],repo:s[2]};const o=r.match(/github\.com\/([^/]+)\/([^/.]+)/);return o?{owner:o[1],repo:o[2]}:null}function ga(e){const t=Ze("gh auth token",e);return t.ok&&t.stdout?t.stdout:ap(e,"GITHUB_TOKEN")}async function zw({request:e}){var t,r,s,o,a,i;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const l=Ce()||process.cwd(),c=await e.json(),u=c.action;if(u==="full-status"){const p=de.existsSync(ee.join(l,".git")),h=de.existsSync(ee.join(l,".gitignore"));let m=!1,f=null,y=!1;if(p){const $=Ze("git remote get-url origin",l);$.ok&&(m=!0,f=$.stdout,y=f.includes("github.com"))}const x=Ze("gh --version",l).ok;let b=!1;x&&(b=Ze("gh auth status",l).ok);const N=!!ap(l,"GITHUB_TOKEN");let w=!1,C=null;const S=ga(l);if(S){const $=await Es("/user",S);$.ok&&(w=!0,C={username:$.data.login,email:$.data.email||""})}const k=Lw(l);let T=!1,_=!1;if(p&&(T=Ze("git rev-parse HEAD",l).ok,T&&m)){const M=Ze("git branch --show-current",l),R=M.ok&&M.stdout?M.stdout:"main";_=Ze(`git rev-parse origin/${R}`,l).ok}return Response.json({ok:!0,gitInitialized:p,hasGitignore:h,hasRemote:m,remoteUrl:f,isGitHub:y,ghCliInstalled:x,ghCliAuthenticated:b,hasToken:N,tokenVerified:w||b,user:C,githubRepo:k,hasCommits:T,pushed:_})}if(u==="init-git"){if(!de.existsSync(ee.join(l,".git"))){const p=Ze("git init",l);if(!p.ok)return Response.json({ok:!1,error:`Failed to initialize git: ${p.stderr}`})}if(!de.existsSync(ee.join(l,".gitignore"))){const p=["node_modules/",".env",".env.local",".env.*.local",".DS_Store","dist/",".next/","*.log",""].join(`
|
|
451
|
+
`);de.writeFileSync(ee.join(l,".gitignore"),p)}return Response.json({ok:!0})}if(u==="save-token"){const p=c.token;if(!p||typeof p!="string")return Response.json({ok:!1,error:"Token is required"});Ow(l,"GITHUB_TOKEN",p);const h=await Es("/user",p);return h.ok?Response.json({ok:!0,saved:!0,user:{username:h.data.login,email:h.data.email||""}}):Response.json({ok:!1,saved:!0,error:`Token saved but verification failed (${h.status})`})}if(u==="list-repos"){const p=ga(l);if(!p)return Response.json({ok:!1,error:"No GitHub authentication found"});const h=await Es("/user/repos?sort=updated&per_page=20&affiliation=owner",p);if(!h.ok)return Response.json({ok:!1,error:"Failed to list repositories"});const m=(h.data||[]).map(g=>({name:g.name,fullName:g.full_name,url:g.html_url,private:g.private,cloneUrl:g.clone_url,sshUrl:g.ssh_url})),f=ee.basename(l).toLowerCase(),y=m.find(g=>g.name.toLowerCase()===f)||null;return Response.json({ok:!0,repos:m,suggestedRepoName:(y==null?void 0:y.name)||null})}if(u==="create-repo"){const p=ga(l);if(!p)return Response.json({ok:!1,error:"No GitHub authentication found"});const h=c.repoName||ee.basename(l),m=c.private!==!1,f=await Es("/user/repos",p,{method:"POST",body:{name:h,private:m,auto_init:!1}});if(!f.ok){const N=((t=f.data)==null?void 0:t.message)||((o=(s=(r=f.data)==null?void 0:r.errors)==null?void 0:s[0])==null?void 0:o.message)||"Failed to create repository";return Response.json({ok:!1,error:N})}const y=f.data;Ze("git remote get-url origin",l).ok?Ze(`git remote set-url origin ${y.clone_url}`,l):Ze(`git remote add origin ${y.clone_url}`,l);try{const N=ee.join(l,".codeyam","config.json"),w=JSON.parse(de.readFileSync(N,"utf8"));w.github={owner:(a=y.owner)==null?void 0:a.login,repo:y.name,repoUrl:y.html_url},de.writeFileSync(N,JSON.stringify(w,null,2))}catch{}const x=Ze("git branch --show-current",l),b=x.ok&&x.stdout?x.stdout:"main",v=Ze(`git push -u origin ${b}`,l);return Response.json({ok:!0,repo:{owner:(i=y.owner)==null?void 0:i.login,name:y.name,url:y.html_url,private:y.private},pushed:v.ok,pushError:v.ok?null:v.stderr})}if(u==="link-repo"){const{repoUrl:p,owner:h,repo:m}=c;if(!p)return Response.json({ok:!1,error:"repoUrl is required"});if(Ze("git remote get-url origin",l).ok){const y=Ze(`git remote set-url origin ${p}`,l);if(!y.ok)return Response.json({ok:!1,error:`Failed to set remote: ${y.stderr}`})}else{const y=Ze(`git remote add origin ${p}`,l);if(!y.ok)return Response.json({ok:!1,error:`Failed to add remote: ${y.stderr}`})}try{const y=ee.join(l,".codeyam","config.json"),g=JSON.parse(de.readFileSync(y,"utf8"));g.github={owner:h||null,repo:m||null,repoUrl:p},de.writeFileSync(y,JSON.stringify(g,null,2))}catch{}return Response.json({ok:!0})}if(u==="push"){const p=Ze("git branch --show-current",l),h=p.ok&&p.stdout?p.stdout:"main",m=Ze(`git push -u origin ${h}`,l);return m.ok?Response.json({ok:!0,branch:h}):Response.json({ok:!1,error:m.stderr||"Push failed"})}return Response.json({ok:!1,error:`Unknown action: ${u}`})}catch(l){const c=l instanceof Error?l.message:String(l);return Response.json({ok:!1,error:c},{status:500})}}const Bw=Object.freeze(Object.defineProperty({__proto__:null,action:zw},Symbol.toStringTag,{value:"Module"}));async function Yw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:o,scenarios:a,includeSessionScenarios:i,screenshot:l,commitSha:c,commitMessage:u}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(a||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!o)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!o}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const p=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=G.join(p,".codeyam","journal");await Pe.mkdir(h,{recursive:!0});const m=new Date,f=m.toISOString().split("T")[0],y=m.toISOString();let g=a||[];const x=G.join(h,"index.json");let b={entries:[]};try{const U=await Pe.readFile(x,"utf8");b=JSON.parse(U)}catch{}let v;i&&b.entries.length>0&&(v=b.entries[b.entries.length-1].time);const N=i?await op(v):a&&a.length>0?await Pw(a):[];i&&N.length>0&&(g=N.map(U=>U.name));const w=await Ba(N,p,m);let C;try{const U=Ce()||process.cwd(),W=await Ye();if(W){const{project:J}=await De(W),D=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",J.id).orderBy("created_at","asc").execute(),L=Tt(D,F=>`${F.name}::${F.url||"/"}`).map(F=>({componentName:F.component_name||null,componentPath:F.component_path||null,pageFilePath:F.page_file_path??null,url:F.url??null,displayName:F.display_name??null})),E=await yr({projectRoot:U,scenarioInputs:L});Object.keys(E.entityChangeStatus).length>0&&(C=E.entityChangeStatus)}}catch{}if(C&&Object.keys(C).length>0){const U=new Set(N.map(J=>J.name)),W=Object.entries(C).filter(([,J])=>J.status==="impacted").map(([J])=>J);if(W.length>0){const J=[],j=new Set(N.map(D=>tn(D)));for(const D of W)j.has(D)||J.push(D);if(J.length>0)try{const D=await Aw(J);if(D.length>0){const A=await Ba(D.filter(L=>!U.has(L.name)),p,m);w.push(...A),g.push(...A.map(L=>L.name))}}catch{}}}let S=w,k=g;if(!i&&C&&Object.keys(C).length>0){S=Ny(w,C);const U=new Set(S.map(W=>W.name));k=g.filter(W=>U.has(W))}const T=$o(p),_=Ri(p);let $;try{const U=gr();U.length>0&&($=U.filter(W=>W.status!=="deleted").map(W=>({path:W.path,status:W.status})))}catch{}const M=G.join(h,`${f}.md`);let R="";try{R=await Pe.readFile(M,"utf8")}catch{R=`# Development Journal — ${f}
|
|
452
|
+
`}const z=Cw({title:r,timeStr:y,type:s,description:o,allScenarioNames:k,screenshot:l||null,scenarioScreenshots:S,commitSha:c||null,commitMessage:u||null,featureName:T,userPrompt:_});await Pe.writeFile(M,R+z,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${M}`);const O={date:f,time:y,title:r,type:s,description:o,scenarios:k,screenshot:l||null,scenarioScreenshots:S,commitSha:c||null,commitMessage:u||null,entityChangeStatus:C,featureName:T,userPrompt:_,modifiedFiles:$};b.entries.push(O),await Pe.writeFile(x,JSON.stringify(b,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${b.entries.length} entries)`);try{await Pe.unlink(G.join(p,"editor-user-prompt.txt"))}catch{}return Nt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${S.length}`),new Response(JSON.stringify({success:!0,entry:O,scenarioScreenshotsFound:S.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Uw=Object.freeze(Object.defineProperty({__proto__:null,action:Yw},Symbol.toStringTag,{value:"Module"}));function Ww({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=Ce()||process.cwd();let a=new URL(e.url).searchParams.get("scenarioId");if(!a){const c=G.join(r,".codeyam","active-scenario.json");if(!q.existsSync(c))return new Response(JSON.stringify({}),{headers:t});a=JSON.parse(q.readFileSync(c,"utf-8")).scenarioId||null}if(!a)return new Response(JSON.stringify({}),{headers:t});const i=G.join(r,".codeyam","editor-scenarios",`${a}.json`);if(!q.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=q.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const Jw=Object.freeze(Object.defineProperty({__proto__:null,loader:Ww},Symbol.toStringTag,{value:"Module"}));async function Hw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Array.isArray(t.paths)?t.paths:[],s=Array.isArray(t.apiRoutes)?t.apiRoutes:[];if(r.length===0&&s.length===0)return new Response(JSON.stringify({error:'At least one entry in "paths" or "apiRoutes" is required.'}),{status:400,headers:{"Content-Type":"application/json"}});const o=globalThis.__codeyam_editor_dev_server__;if(!o||!o.url||o.status!=="running")return new Response(JSON.stringify({error:`Dev server is not running. Start it with: codeyam editor dev-server '{"action":"start"}'`}),{status:503,headers:{"Content-Type":"application/json"}});const a=o.url,i=1e4,l={},c={};let u=!0;for(const f of r)try{const y=await fetch(`${a}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(u=!1),l[f]={status:y.status,ok:g}}catch(y){u=!1,l[f]={status:0,ok:!1,error:y.message}}for(const f of s)try{const y=await fetch(`${a}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(u=!1);let x=!1,b;try{const v=await y.text();JSON.parse(v),x=!0,b=v.length>200?v.slice(0,200)+"…":v}catch{}c[f]={status:y.status,ok:g,isJSON:x,preview:b}}catch(y){u=!1,c[f]={status:0,ok:!1,isJSON:!1,error:y.message}}const p=r.length+s.length,h=Object.values(l).filter(f=>f.ok).length+Object.values(c).filter(f=>f.ok).length,m=u?`All ${p} routes OK`:`${h}/${p} routes passed`;return new Response(JSON.stringify({ok:u,routes:l,apiRoutes:c,summary:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-verify-routes] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Vw=Object.freeze(Object.defineProperty({__proto__:null,action:Hw},Symbol.toStringTag,{value:"Module"}));async function Kw(e,t){const r=Ce();if(!r)return{entityCalls:[],analysisCalls:[]};const s=G.join(r,".codeyam","llm-calls");try{await Pe.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],a=[];try{const l=(await Pe.readdir(s)).filter(b=>b.endsWith(".json")),c=`${e}_`,u=t?`${t}_`:null,p=[],h=[];for(const b of l)b.startsWith(c)||u&&b.startsWith(u)?p.push(b):h.push(b);const m=p.map(async b=>{try{const v=G.join(s,b),N=await Pe.readFile(v,"utf-8");return JSON.parse(N)}catch{return null}}),f=h.map(async b=>{try{const v=G.join(s,b),N=await Pe.readFile(v,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(m),Promise.all(f)]),x=[...y,...g].filter(b=>b!==null);for(const b of x)b.object_id===e?o.push(b):t&&b.object_id===t&&a.push(b);o.sort((b,v)=>v.created_at-b.created_at),a.sort((b,v)=>v.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:a}}async function Gw({params:e,request:t}){const{entitySha:r}=e;if(!r)return le({error:"Entity SHA is required"},{status:400});const o=new URL(t.url).searchParams.get("analysisId")||void 0,a=await Kw(r,o);return le(a)}const qw=Object.freeze(Object.defineProperty({__proto__:null,loader:Gw},Symbol.toStringTag,{value:"Module"}));function Qw(){try{const e=Ce()||process.cwd(),t=ee.join(e,".codeyam","config.json");if(!de.existsSync(t))return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,projectScreenSizes:null,appFormats:null,hosting:null,github:null});const r=JSON.parse(de.readFileSync(t,"utf8"));return Response.json({projectTitle:r.projectTitle||null,projectDescription:r.projectDescription||null,defaultScreenSize:r.defaultScreenSize||null,screenSizes:r.screenSizes||null,projectScreenSizes:r.projectScreenSizes||null,appFormats:r.appFormats||null,techStack:r.techStack||null,hosting:r.hosting||null,github:r.github||null,environmentVariables:r.environmentVariables||[]})}catch{return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,appFormats:null,techStack:null,hosting:null,github:null,environmentVariables:[]})}}async function Zw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");if(!de.existsSync(r))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const s=await e.json(),o=JSON.parse(de.readFileSync(r,"utf8"));if(s.projectTitle!==void 0&&(o.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(o.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(o.defaultScreenSize=s.defaultScreenSize),s.screenSizes!==void 0&&(o.screenSizes=s.screenSizes),s.appFormats!==void 0&&(o.appFormats=s.appFormats),s.techStack!==void 0&&(o.techStack=s.techStack),s.projectScreenSizes!==void 0&&(o.projectScreenSizes=s.projectScreenSizes),s.hosting!==void 0&&(o.hosting=s.hosting),s.github!==void 0&&(o.github=s.github),s.addEnvironmentVariable){const a=o.environmentVariables||[],{key:i,value:l}=s.addEnvironmentVariable,c=a.findIndex(u=>(u.key||u.name)===i);c>=0?a[c]={key:i,value:l}:a.push({key:i,value:l}),o.environmentVariables=a}if(s.screenSizes&&!s.defaultScreenSize)for(const[a,i]of Object.entries(s.screenSizes)){const l=i;if(l.default){o.defaultScreenSize={name:a,width:l.width,height:l.height},s.defaultScreenSize=o.defaultScreenSize;break}}return de.writeFileSync(r,JSON.stringify(o,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&Ti(s.defaultScreenSize),Nt.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:o.projectTitle||null,projectDescription:o.projectDescription||null,defaultScreenSize:o.defaultScreenSize||null,screenSizes:o.screenSizes||null,projectScreenSizes:o.projectScreenSizes||null,appFormats:o.appFormats||null,techStack:o.techStack||null,hosting:o.hosting||null,github:o.github||null,environmentVariables:o.environmentVariables||[]}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Xw=Object.freeze(Object.defineProperty({__proto__:null,action:Zw,loader:Qw},Symbol.toStringTag,{value:"Module"}));function ip(e){try{const t=G.join(e,"package.json"),r=JSON.parse(q.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function eN(e,t){var i;const s=JSON.parse(t).testResults||[],o=[];for(const l of s)for(const c of l.assertionResults||[]){const u=c.ancestorTitles||[],p=c.title||c.fullName||"unknown",h=u.length>0?`${u.join(" > ")} > ${p}`:p;o.push({title:p,fullName:h,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const a=o.some(l=>l.status==="failed");return{testFilePath:e,status:a?"failed":"passed",testCases:o}}function tN(e,t,r){var l;const o=JSON.parse(r).testResults||[],a=new Map;for(const c of o){const u=c.name||"",p=a.get(u);p?p.push(c):a.set(u,[c])}const i={};e.endsWith("/")||e+"";for(const c of t){const u=G.isAbsolute(c)?c:G.join(e,c),p=a.get(u);if(!p||p.length===0){i[c]={testFilePath:c,status:"error",testCases:[],errorMessage:`File not found in test output: ${c}`};continue}const h=[];for(const f of p)for(const y of f.assertionResults||[]){const g=y.ancestorTitles||[],x=y.title||y.fullName||"unknown",b=g.length>0?`${g.join(" > ")} > ${x}`:x;h.push({title:x,fullName:b,status:y.status==="passed"?"passed":y.status==="failed"?"failed":"skipped",duration:y.duration,failureMessages:(l=y.failureMessages)!=null&&l.length?y.failureMessages:void 0})}const m=h.some(f=>f.status==="failed");i[c]={testFilePath:c,status:m?"failed":"passed",testCases:h}}return i}function nN(e,t,r){return e==="vitest"?{cmd:"node",args:["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",t,...r]}:{cmd:"./node_modules/.bin/jest",args:["--json","--outputFile",t,...r]}}async function rN(e,t){if(t.length===0)return{};const r=ip(e);if(!r){const c={};for(const u of t)c[u]={testFilePath:u,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};return c}const s=[],o={};for(const c of t){const u=G.isAbsolute(c)?c:G.join(e,c);q.existsSync(u)?s.push(c):o[c]={testFilePath:c,status:"error",testCases:[],errorMessage:"Test file not found"}}if(s.length===0)return o;const a=G.join(io.tmpdir(),`codeyam-test-result-${Date.now()}.json`),{cmd:i,args:l}=nN(r,a,s);return new Promise(c=>{var m;const u=kt(i,l,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(m=u.stderr)==null||m.on("data",f=>{p+=f.toString()});const h=setTimeout(()=>{u.kill("SIGTERM");for(const f of s)o[f]={testFilePath:f,status:"error",testCases:[],errorMessage:"Test timed out after 60 seconds"};c(o)},6e4);u.on("close",()=>{clearTimeout(h);try{const f=q.readFileSync(a,"utf8");q.unlinkSync(a);const y=tN(e,s,f);Object.assign(o,y)}catch{for(const f of s)o[f]={testFilePath:f,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"}}c(o)}),u.on("error",f=>{clearTimeout(h);for(const y of s)o[y]={testFilePath:y,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${f.message}`};c(o)})})}async function sN(e,t){const r=ip(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=G.isAbsolute(t)?t:G.join(e,t);if(!q.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const o=G.join(io.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(a=>{var h;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",o,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",o,"--testPathPatterns",t]);const c=kt(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let u="";(h=c.stderr)==null||h.on("data",m=>{u+=m.toString()});const p=setTimeout(()=>{c.kill("SIGTERM"),a({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(p);try{const m=q.readFileSync(o,"utf8");q.unlinkSync(o),a(eN(t,m))}catch{a({testFilePath:t,status:"error",testCases:[],errorMessage:u.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",m=>{clearTimeout(p),a({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${m.message}`})})})}function yc(){return{version:1,results:{}}}function lp(e,t,r){return e.sourceHash!==t||e.testHash!==r}function oN(e,t,r){return{testFilePath:e.testFilePath,status:e.status,testCases:e.testCases,...e.errorMessage?{errorMessage:e.errorMessage}:{},sourceHash:t,testHash:r,timestamp:new Date().toISOString()}}function aN(e,t){return{version:1,results:{...e.results,...t}}}const cp="test-results.json";function Li(e){const t=G.join(e,".codeyam",cp);try{const r=q.readFileSync(t,"utf8"),s=JSON.parse(r);return s&&s.version===1&&s.results?s:yc()}catch{return yc()}}function iN(e,t){const r=G.join(e,".codeyam");q.mkdirSync(r,{recursive:!0});const s=G.join(r,cp);q.writeFileSync(s,JSON.stringify(t,null,2)+`
|
|
453
|
+
`)}function xc(e){try{const t=q.readFileSync(e);return Za.createHash("sha256").update(t).digest("hex")}catch{return""}}function zi(e,t){const r={};for(const s of t){const o=G.join(e,s.filePath),a=G.join(e,s.testFile);r[s.testFile]={sourceHash:xc(o),testHash:xc(a)}}return r}function dp(e,t,r){const s=Li(e),o=zi(e,r),a={};for(const[l,c]of Object.entries(t)){const u=o[l];u&&(a[l]=oN(c,u.sourceHash,u.testHash))}const i=aN(s,a);iN(e,i)}async function lN({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=Ce()||process.cwd();try{const o=await sN(s,r);try{const a=G.join(s,".codeyam","glossary.json"),i=q.readFileSync(a,"utf8"),c=Co(JSON.parse(i)).find(u=>u.testFile===r);c&&dp(s,{[r]:o},[{filePath:c.filePath,testFile:r}])}catch{}return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}catch(o){const a=o instanceof Error?o.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:a}),{status:500,headers:{"Content-Type":"application/json"}})}}const cN=Object.freeze(Object.defineProperty({__proto__:null,loader:lN},Symbol.toStringTag,{value:"Module"}));function bc(e,t){var r,s;try{return((s=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(o){return console.error(`Failed to get commit SHA for ${e}:`,o),""}}function dN(e,t,r,s){const o=dr.createHash("sha256");return o.update(`${e}:${t}:${r}:${s}`),o.digest("hex").substring(0,16)}function up(){const e=Ce();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return de.existsSync(t)||de.mkdirSync(t,{recursive:!0}),t}function uN(e){try{const t=up(),r=ee.join(t,`${e}.json`);if(!de.existsSync(r))return null;const s=de.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function pN(e,t){try{const r=up(),s=ee.join(r,`${e}.json`);de.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function hN(e,t,r){const s=qs(t,e),o=qs(r,e),a=new Map(s.map(p=>[p.name,p])),i=new Map(o.map(p=>[p.name,p])),l=[],c=[],u=[];for(const[p,h]of i){const m=a.get(p);m?m.sha!==h.sha&&c.push({name:p,baseSha:m.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[p,h]of a)i.has(p)||u.push(h);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:u}}function mN(e,t){const r=Ce();if(!r)throw new Error("No project root found");const s=bc(e,r),o=bc(t,r);if(!s||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const a=dN(e,t,s,o),i=uN(a);if(i)return console.log(`Using cached branch entity diff: ${a}`),i;const l=Hu(e,t),c=[];for(const p of l)if(p.path.match(/\.(tsx?|jsx?)$/))if(p.status==="deleted"){const h=Os(p.path,e,t),m=qs(h.oldContent,p.path);c.push({filePath:p.path,newEntities:[],modifiedEntities:[],deletedEntities:m})}else if(p.status==="added"){const h=Os(p.path,e,t),m=qs(h.newContent,p.path);c.push({filePath:p.path,newEntities:m,modifiedEntities:[],deletedEntities:[]})}else{const h=Os(p.path,e,t),m=hN(p.path,h.oldContent,h.newContent);(m.newEntities.length>0||m.modifiedEntities.length>0||m.deletedEntities.length>0)&&c.push(m)}const u={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:o,fileComparisons:c,cacheKey:a,computedAt:new Date().toISOString()};return pN(a,u),u}function fN({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return le({error:"Missing required parameters: base and compare"},{status:400});const o=mN(r,s);return le(o)}catch(t){return console.error("Failed to compute branch entity diff:",t),le({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const gN=Object.freeze(Object.defineProperty({__proto__:null,loader:fN},Symbol.toStringTag,{value:"Module"}));async function yN({request:e}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:o,viewportWidth:a=1440}=t;if(!r||!s||!o)return le({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=Ce();if(!i)return le({error:"Project root not found"},{status:500});const l=G.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:o,projectRoot:i,viewportWidth:a}),u=await new Promise(m=>{const f=G.join(i,".codeyam","db.sqlite3"),y=kt("npx",["tsx",l,c],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",b=>{const v=b.toString();g+=v;const N=v.trim().split(`
|
|
454
|
+
`);for(const w of N)w.includes("[Capture]")&&console.log(w)}),y.stderr.on("data",b=>{const v=b.toString();x+=v,console.error("[Capture:Error]",v.trim())}),y.on("close",b=>{m(b===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${b}`})}),y.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),m({success:!1,output:"",error:b.message})})});if(!u.success)return le({error:"Failed to capture screenshot",details:u.error},{status:500});const p=u.output.match(/\[Capture\] RESULT:(.+)/);if(!p)return le({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(p[1]);return le(h)}catch(t){return console.error("[Capture] Error:",t),le({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const xN=Object.freeze(Object.defineProperty({__proto__:null,action:yN},Symbol.toStringTag,{value:"Module"}));function bN(e){const t=e||process.cwd();try{return Me("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function vN(e){const t=e||process.cwd();try{return Me("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function wN(e){if(vN(e))return!1;Me("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Me('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Me('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function NN(e){Me("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function SN(e,t){return Me(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),bN(e)}function CN(e){return/^[0-9a-f]{7,40}$/i.test(e)}function kN(e,t){try{return Me(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function EN(e,t){try{return{stashed:!Me(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function _N(e,t){Me(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function jN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!CN(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!kN(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:o}=EN(s,"codeyam: auto-stash before time travel");o&&console.log("[editor-load-commit] Stashed uncommitted changes");try{_N(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(a){const i=a instanceof Error?a.message:String(a);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(a){console.warn("[editor-load-commit] Dev server restart warning:",a)}return new Response(JSON.stringify({success:!0,stashed:o}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const PN=Object.freeze(Object.defineProperty({__proto__:null,action:jN},Symbol.toStringTag,{value:"Module"}));async function AN(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await We();const s=await Xt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=$e(),a=s.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",a).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await o.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",a).execute(),console.log(`[recapture] Updated defaultWidth for entity ${a} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await pr(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const c=Ce();if(!c)throw new Error("Project root not found");const u=G.join(c,".codeyam","config.json"),p=JSON.parse(q.readFileSync(u,"utf8")),{projectSlug:h}=p;if(!h)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${m}`),{jobId:m}}async function TN(e,t,r){var p;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await We();const s=await Xt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const o=(p=s.scenarios)==null?void 0:p.find(h=>h.id===t);if(!o)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${o.name}`),await pr(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const m=h.scenarios.find(f=>f.name===o.name);m&&(delete m.finishedAt,delete m.startedAt,delete m.error,delete m.errorStack,delete m.screenshotStartedAt,delete m.screenshotFinishedAt,delete m.interactiveStartedAt,delete m.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${o.name} for recapture`);const a=Ce();if(!a)throw new Error("Project root not found");const i=G.join(a,".codeyam","config.json"),l=JSON.parse(q.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:u}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${u}`),{jobId:u}}async function MN({request:e,context:t}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await en()),!r)return le({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("scenarioId");if(!o||!a)return le({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${a}`);const i=await TN(o,a,r);return console.log("[API] Scenario recapture queued",i),le({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),le({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const $N=Object.freeze(Object.defineProperty({__proto__:null,action:MN},Symbol.toStringTag,{value:"Module"}));async function Ya(e){try{return await Ae.stat(e),!0}catch{return!1}}async function pp(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Ae.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function FN(){return`/private/tmp/claude-501/-${(Ce()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Ls="/tmp/claude-rule-markers",RN=/<system-reminder>[\s\S]*?<\/system-reminder>/g,vc=2e3;function DN(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||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${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 IN=["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 ON(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const o=String(s.input.file_path||"");if(o.includes(".claude/rules/")){const a=o.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${a}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:a,content:String(s.input.content||"")}):t.push({action:"modified",filePath:a,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const o=String(s.input.command||"");if(o.includes("codeyam memory touch")){const a=`touch:${o}`;r.has(a)||(r.add(a),t.push({action:"touched",filePath:o}))}}}return t}function LN(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const o=s.indexOf(`
|
|
455
|
+
###`);return o!==-1&&(s=s.slice(0,o).trim()),s||void 0}function zN(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of IN)if(r.includes(s))return!0}return!1}function BN(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const o=(s.message||{}).model;if(typeof o=="string"&&o)return o}}catch{continue}}}function YN(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const o={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(o.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(o.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(o.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(o.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){o.usage={};for(const a of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[a]=="number"&&(o.usage[a]=s.usage[a])}return Array.isArray(s.errors)&&s.errors.length>0&&(o.errors=s.errors.map(String)),o}catch{continue}}}function UN(e){const t=[],r={};for(const s of e){const o=s.trim();if(!o)continue;let a;try{a=JSON.parse(o)}catch{continue}const i=a.type;if(i==="progress"||i==="system"||i==="result")continue;const c=(a.message||{}).content,u=a.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:u,agent_id:String(a.agentId||a.session_id||"unknown"),slug:String(a.slug||"")});else if(Array.isArray(c)){for(const p of c)if(typeof p=="object"&&p!==null&&p.type==="tool_result"){const h=p,m=String(h.tool_use_id||"");let f=h.content;const y=!!h.is_error;typeof f=="string"&&(f=f.replace(RN,"").trim()),t.push({type:"tool_result",tool_use_id:m,tool_name:r[m]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:u})}}}else if(i==="assistant"&&Array.isArray(c))for(const p of c){if(typeof p!="object"||p===null)continue;const h=p;if(h.type==="text"){const m=String(h.text||"").trim();m&&t.push({type:"assistant_text",text:m,timestamp:u})}else if(h.type==="tool_use"){const m=String(h.id||""),f=String(h.name||"unknown"),y=h.input||{};r[m]=f,t.push({type:"tool_call",tool_use_id:m,name:f,input:y,timestamp:u})}}}return t}function WN(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}const Zn=20;async function wc(e){const r=(await Ae.readFile(e.filePath,"utf-8")).split(`
|
|
456
|
+
`),s=UN(r);if(s.length===0)return null;const o=s.find(N=>N.type==="user_prompt"),a=e.stem,i=BN(r);let l=(o==null?void 0:o.slug)||"",c=(o==null?void 0:o.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let u;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await Ya(N))try{u=await Ae.readFile(N,"utf-8")}catch{}}const p=s.filter(N=>N.type==="tool_call").length,h=s.filter(N=>N.type==="assistant_text").length,m=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=m.length,y=m.map(N=>{const w=N.content||"Unknown error";return w.length>150?w.slice(0,150)+"...":w});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=DN(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>vc&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,vc));const g=ON(s),x=zN(s),b=LN(u),v=YN(r);return{id:a,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:p,textBlocks:h,errors:f,errorMessages:y},entries:s,context:u,conversationSnippet:b,ruleChanges:g,hasConfusion:x,sessionResult:v}}async function JN(){const e=FN(),t=Ls,r=[];if(await Ya(e)){const i=await Ae.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=ee.join(e,l),u=await Ae.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:u.mtimeMs})}}const s=new Set,o=await pp(),a=[];o&&a.push(ee.join(t,o)),a.push(t);for(const i of a){if(!await Ya(i))continue;const l=await Ae.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const u=ee.join(i,c),p=await Ae.stat(u);r.push({filePath:u,stem:c.replace(".log",""),mtime:p.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function HN({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",o=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),a=await JN();if(!s){const p=a.length,h=(o-1)*Zn,m=a.slice(h,h+Zn),f=[];for(const y of m){const g=await wc(y);g&&f.push(g)}return Response.json({agents:f,total:p,page:o,pageSize:Zn})}const i=[];for(const p of a){const h=await wc(p);if(!h)continue;(h.id.toLowerCase().includes(s)||h.slug.toLowerCase().includes(s)||h.entries.some(f=>WN(f,s)))&&i.push(h)}const l=i.length,c=(o-1)*Zn,u=i.slice(c,c+Zn);return Response.json({agents:u,total:l,page:o,pageSize:Zn})}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 VN=Object.freeze(Object.defineProperty({__proto__:null,loader:HN},Symbol.toStringTag,{value:"Module"})),hp="__codeyam_editor_dev_server__",Nc=30;function Bi(){return globalThis[hp]??null}function mp(e){globalThis[hp]=e}function _s(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{de.existsSync(s)&&(de.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(o){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,o)}if(t)try{const s=Me(`lsof -ti:${t}`,{encoding:"utf8"}).trim();if(s){const o=process.pid,a=s.split(`
|
|
457
|
+
`).filter(i=>i&&parseInt(i,10)!==o);if(a.length>0){for(const i of a)try{Me(`kill ${i}`)}catch{}console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${a.join(", ")}`)}}}catch{}}function KN({request:e}){const t=Bi();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Fu(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function GN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?Ua():r==="stop"?Sc():r==="restart"?(Sc(),await new Promise(s=>setTimeout(s,1e3)),Ua()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function qN(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const o=ee.dirname(t);if(ee.basename(o)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:o;break}t=o}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(de.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Ua(e=!1){var k,T;const t=Bi();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=Ce()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:o,devServerPort:a}=Eu(s),i=tx(r,a);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:c,env:u}=i;_s(r,a),_s(r,3e3),_s(r,3001),_s(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const p=qN(),h=p?`--import ${p}`:"",{NODE_OPTIONS:m,PORT:f,CODEYAM_PORT:y,...g}=process.env,x={};for(const _ of[".env",".env.local",".env.development",".env.development.local"])try{const $=ee.join(r,_);if(!de.existsSync($))continue;const M=de.readFileSync($,"utf-8");for(const R of M.split(`
|
|
458
|
+
`)){const z=R.trim();if(!z||z.startsWith("#"))continue;const O=z.indexOf("=");if(O===-1)continue;const U=z.slice(0,O).trim();let W=z.slice(O+1).trim();(W.startsWith('"')&&W.endsWith('"')||W.startsWith("'")&&W.endsWith("'"))&&(W=W.slice(1,-1)),U&&(x[U]=W)}}catch{}const b={};try{const _=ee.join(r,".codeyam","config.json"),$=JSON.parse(de.readFileSync(_,"utf-8"));for(const M of $.environmentVariables||[])M.key&&M.value!==void 0&&(b[M.key]=M.value)}catch{}const v=kt(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...g,...x,...b,FORCE_COLOR:"1",BROWSER:"none",...h?{NODE_OPTIONS:h}:{},CODEYAM_PROXY_URL:`http://localhost:${o}`,...u},detached:!0});v.unref();const N=e?((t==null?void 0:t.retryCount)??0)+1:0,w={process:v,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:v.pid||0,startedAt:Date.now(),retryCount:N};mp(w);const C=(_,$)=>{const M=_.toString(),R=M.split(`
|
|
459
|
+
`).filter(z=>z.trim());if(R.length>0&&(w.stderrBuffer.push(...R),w.stderrBuffer.length>Nc&&(w.stderrBuffer=w.stderrBuffer.slice(-Nc))),w.status==="starting"){const z=rx(M);z&&(w.url=z,w.status="running",console.log(`[editor-dev-server] URL detected: ${w.url}`),Da({port:o,targetUrl:w.url}).then(()=>rc()))}};(k=v.stdout)==null||k.on("data",_=>C(_)),(T=v.stderr)==null||T.on("data",_=>C(_));const S=parseInt(u.PORT||"0",10);return S>0&&(async()=>{if(await new Promise($=>setTimeout($,1e4)),w.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${S}...`);const _=await ox(S,{intervalMs:2e3,maxAttempts:15});_&&w.status==="starting"&&(w.url=_,w.status="running",console.log(`[editor-dev-server] URL detected via polling: ${w.url}`),Da({port:o,targetUrl:w.url}).then(()=>rc()))})(),v.on("exit",_=>{console.log(`[editor-dev-server] Process exited with code ${_}`);const $=Date.now()-w.startedAt,M=w.status==="running",R=ax({exitCode:_??null,uptime:$,retryCount:w.retryCount,wasRunning:M});if(R.action==="retry")console.log(`[editor-dev-server] Quick failure (${$}ms), auto-retrying...`),w.status="stopped",Ua(!0);else if(R.action==="error"){w.status="error";const z=w.stderrBuffer.length>0?w.stderrBuffer.join(`
|
|
460
|
+
`):"",O=M?`Dev server exited with code ${_}`:`Dev server exited (code ${_}) before it started serving`;w.errorMessage=z?`${O}
|
|
461
|
+
|
|
462
|
+
${z}`:O,console.error(`[editor-dev-server] Server failed: ${w.errorMessage}`)}else w.status="stopped"}),v.on("error",_=>{console.error("[editor-dev-server] Process error:",_),w.status="error",w.errorMessage=_.message}),new Response(JSON.stringify({status:"starting",pid:v.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function Sc(){const e=Bi();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Lu();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",mp(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const QN=Object.freeze(Object.defineProperty({__proto__:null,action:GN,loader:KN},Symbol.toStringTag,{value:"Module"}));async function ZN({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 s=Qr(r);try{return await Rr(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(o){console.error("[api.logs] Error clearing log file:",o);const a=o instanceof Error?o.message:String(o);return new Response(`Error clearing log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function XN({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Qr(t);try{if(!Pt(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await ja(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const e1=Object.freeze(Object.defineProperty({__proto__:null,action:ZN,loader:XN},Symbol.toStringTag,{value:"Module"}));function t1({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=Ce()||process.cwd(),o=G.resolve(s,r);if(!o.startsWith(s+G.sep)&&o!==s)return Response.json({error:"Path outside project root"},{status:403});const a=Vu(r,s);return Response.json(a)}const n1=Object.freeze(Object.defineProperty({__proto__:null,loader:t1},Symbol.toStringTag,{value:"Module"}));async function r1(){const e=await Ye();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await De(e),r=$e(),s=process.env.CODEYAM_PORT||"3111",o=Ce()||process.cwd(),a=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","screenshot_path","page_file_path","display_name"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=Tt(a,u=>`${u.name}::${u.url||"/"}`);let l={};try{const u=i.map(h=>({componentName:h.component_name||null,componentPath:h.component_path||null,pageFilePath:h.page_file_path??null,url:h.url??null,displayName:h.display_name??null}));l=(await yr({projectRoot:o,scenarioInputs:u})).entityChangeStatus}catch{}const c=i.map(u=>{const p=u,h=tn({componentName:u.component_name,pageFilePath:p.page_file_path,url:p.url}),m=h?l[h]:void 0;return{id:u.id,name:u.name,componentName:u.component_name||null,type:u.type||null,changeStatus:(m==null?void 0:m.status)||null,screenshotPath:u.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${u.id}&ref=link`}});return Response.json({scenarios:c})}const s1=Object.freeze(Object.defineProperty({__proto__:null,loader:r1},Symbol.toStringTag,{value:"Module"}));async function o1(e,t){var a,i,l,c,u,p;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await We();const r=await Xt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(a=r.scenarios)==null?void 0:a.find(h=>h.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const o={returnValue:{status:"success",data:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((p=(u=s.metadata)==null?void 0:u.data)==null?void 0:p.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),o}async function a1({request:e}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return le({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const o=await o1(r,s);return console.log("[API] Function execution completed successfully"),le({success:!0,result:o})}catch(t){return console.log("[API] Error during function execution:",t),le({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const i1=Object.freeze(Object.defineProperty({__proto__:null,action:a1},Symbol.toStringTag,{value:"Module"}));function l1({request:e}){return le({status:"ok"})}async function c1({request:e,context:t}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await en()),!r)return console.error("[Interactive Mode API] Queue not initialized"),le({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("action"),a=s.get("analysisId"),i=s.get("scenarioId");if(!o||!a)return le({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return le({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Ye();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return le({error:"Project not initialized"},{status:500});if(o==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:a,scenarioId:i,projectSlug:l});return le({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:a,projectSlug:l});return le({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}catch(s){console.error("[Interactive Mode API] Error:",s);const o=s instanceof Error?s.message:String(s),a=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",a),le({error:"Failed to control interactive mode",details:o},{status:500})}}const d1=Object.freeze(Object.defineProperty({__proto__:null,action:c1,loader:l1},Symbol.toStringTag,{value:"Module"}));async function u1({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const o=Ce();if(o)for(const a of s){const i=ee.join(o,".codeyam","captures","screenshots",a);try{await Ae.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await ug({ids:[r]});try{await $e().deleteFrom("editor_scenarios").where("id","=",r).execute()}catch{}try{const o=Ce()||process.cwd();nb(o,r)}catch{}return 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 p1=Object.freeze(Object.defineProperty({__proto__:null,action:u1},Symbol.toStringTag,{value:"Module"}));class h1 extends Gr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const Wa="__codeyam_dev_mode_event_emitter__";if(!globalThis[Wa]){const e=new h1;e.setMaxListeners(20),globalThis[Wa]=e}const Cc=globalThis[Wa];function m1({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
463
|
+
|
|
464
|
+
`));let o=!1;const a=()=>{if(!o){o=!0,Cc.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
|
|
465
|
+
|
|
466
|
+
`))}catch{a()}};Cc.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
467
|
+
|
|
468
|
+
`))}catch{a()}},3e4);e.signal.addEventListener("abort",a)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const f1=Object.freeze(Object.defineProperty({__proto__:null,loader:m1},Symbol.toStringTag,{value:"Module"})),Jr="/tmp/codeyam",Ja=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",fp=500,g1=fp*1024*1024;function Tn(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function zs(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function gp(e){return Tn("config user.email",e)}function y1(e){const t=G.join(e,".codeyam","debug-report.md");if(!q.existsSync(t))return null;try{return q.readFileSync(t,"utf8")}catch{return null}}function x1(e,t=20){const r=G.join(Jr,"local-dev",e,"codeyam","log.txt");if(!q.existsSync(r))return[];try{return q.readFileSync(r,"utf8").split(`
|
|
469
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function b1(e){try{const t=await fetch(`${Ja}/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 v1(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 w1(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:o,screenshot:a,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),u=G.join(Jr,`delta-staging-${c}`),p=G.join(u,"delta");q.mkdirSync(p,{recursive:!0});try{const h=Tn("diff --binary HEAD",t)||"";q.writeFileSync(G.join(p,"tracked.patch"),h?h+`
|
|
470
|
+
`:"");const m=Tn("ls-files --others --exclude-standard",t);if(m){const x=G.join(p,"untracked");q.mkdirSync(x,{recursive:!0});for(const b of m.split(`
|
|
471
|
+
`).filter(Boolean)){const v=G.join(t,b),N=G.join(x,b);if(q.existsSync(v)){const w=G.dirname(N);q.mkdirSync(w,{recursive:!0}),q.statSync(v).isFile()&&q.copyFileSync(v,N)}}}const f=G.join(t,".codeyam");if(q.existsSync(f)){const x=G.join(p,"codeyam");q.cpSync(f,x,{recursive:!0})}q.writeFileSync(G.join(p,"meta.json"),JSON.stringify(o,null,2));const y=G.join(Jr,"local-dev",r,"codeyam","log.txt");q.existsSync(y)?q.copyFileSync(y,G.join(p,"codeyam-log.txt")):q.writeFileSync(G.join(p,"codeyam-log.txt"),`# Log file not found
|
|
472
|
+
`);const g=G.join(t,".codeyam","debug-report.md");q.existsSync(g)&&(q.copyFileSync(g,G.join(p,"debug-report.md")),l("Debug report included")),a&&a.length>0&&(q.writeFileSync(G.join(p,"screenshot.jpg"),a),l(`Screenshot included (${zs(a.length)})`));try{Me(`tar -czf "${s}" -C "${u}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{q.rmSync(u,{recursive:!0,force:!0})}}async function N1(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:o,onProgress:a}=e,i=a||(()=>{});i("Gathering metadata...");const l=Tn("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 c=Tn("rev-parse --abbrev-ref HEAD",t)||"unknown",u=Tn("status --porcelain",t),p=Tn("remote get-url origin",t),h=u!==null&&u.length>0,m=cu(r),f=y1(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:c,isDirty:h,remoteUrl:p},versions:{cli:m.cliVersion,webserver:m.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),b=G.join(Jr,`base-${l}-${x}.tar.gz`),v=G.join(Jr,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await b1(l);let w=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),v1(t,b),w=q.statSync(b).size,i(`Base archive: ${zs(w)}`)),i("Generating delta archive..."),w1({projectRoot:t,projectSlug:r,outputPath:v,metadata:g,screenshot:o,onProgress:a});const S=q.statSync(v).size;i(`Delta archive: ${zs(S)}`);const k=(w||0)+S;if(k>g1)throw q.existsSync(b)&&q.unlinkSync(b),q.unlinkSync(v),new Error(`Bundle too large: ${zs(k)} (max: ${fp} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:b,deltaPath:v,metadata:g,baseSha:l,baseSize:w,deltaSize:S}}async function S1(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:o,baseSha:a,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),u=q.statSync(r),p=t?q.statSync(t):null,h=u.size+((p==null?void 0:p.size)||0);c("Requesting upload URLs...");const m=await fetch(`${Ja}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:h,baseSha:a,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:o.timestamp,git:o.git,versions:o.versions,system:o.system,feedback:o.feedback}})});if(!m.ok){const N=await m.json();throw new Error(N.error||`Server returned ${m.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await m.json(),x=[];if(t&&g){c("Uploading base...");const N=q.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}c("Uploading delta...");const b=q.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),c("Confirming upload...");const v=await fetch(`${Ja}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const N=await v.json();throw new Error(N.error||`Confirm failed: ${v.status}`)}return t&&q.existsSync(t)&&q.unlinkSync(t),q.unlinkSync(r),{bundleId:f}}async function C1({request:e}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),o=t.get("email"),a=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),c=t.get("analysisId"),u=t.get("currentUrl"),p=t.get("entityName"),h=t.get("entityType"),m=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&p&&(m?g=`Issue on ${p} scenario "${m}"`:g=`Issue on ${p}`);let x;if(y&&y.size>0){const k=await y.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const b=Ce();if(!b)return le({error:"Project root not found"},{status:500});const v=await Ye();if(!v)return le({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:o||void 0,source:a||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:u||void 0,recentActivity:x1(v,20),entityName:p||void 0,entityType:h||void 0,scenarioName:m||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${v}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const w=await N1({projectRoot:b,projectSlug:v,feedback:N,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),C=(w.baseSize||0)+w.deltaSize;console.log(`[Bundle] Archives created: delta=${w.deltaSize} bytes${w.basePath?`, base=${w.baseSize} bytes`:" (base reused)"}`);const S=await S1({basePath:w.basePath,deltaPath:w.deltaPath,projectSlug:v,metadata:w.metadata,baseSha:w.baseSha,deltaSize:w.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${S.bundleId}`),le({success:!0,reportId:S.bundleId,size:C})}catch(t){return console.error("[Bundle] Error:",t),le({error:t.message||"Failed to generate bundle"},{status:500})}}function k1(){const e=Ce(),t=e?gp(e):null;return le({defaultEmail:t})}const E1=Object.freeze(Object.defineProperty({__proto__:null,action:C1,loader:k1},Symbol.toStringTag,{value:"Module"})),_1={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"};function j1(e){var r;return e.length<4?null:((r=e.slice(3).split(" -> ").pop())==null?void 0:r.trim())||""||null}function P1(e){const t=e.slice(0,2);return t==="??"?"untracked":t.includes("D")?"deleted":t.includes("A")?"added":t.includes("R")?"renamed":(t.includes("M"),"modified")}function kc(e){const{projectRoot:t,previousProvider:r,newProvider:s,handoff:o}=e,a=[];try{const c=Me("git status --porcelain",{cwd:t,encoding:"utf8"}).split(`
|
|
473
|
+
`).filter(Boolean);for(const u of c){const p=j1(u);p&&!p.startsWith(".codeyam/")&&a.push({path:p,status:P1(u)})}}catch{}const i=(o==null?void 0:o.lastStep)??null;return{previousProvider:r,newProvider:s,lastStep:i,lastStepLabel:i?_1[i]||"Unknown":null,handoffSummary:(o==null?void 0:o.summary)??null,stepHistory:(o==null?void 0:o.stepHistory)??[],uncommittedChanges:{summary:`${a.length} files changed`,files:a},generatedAt:new Date().toISOString()}}const ya=30;function xa(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ec(e){const t=[];t.push("## Provider Handoff"),t.push("");const r=e.lastStep?` reached **Step ${e.lastStep} (${e.lastStepLabel})**`:"";if(t.push(`You are continuing work started by **${xa(e.previousProvider)}** (now using **${xa(e.newProvider)}**).`),r&&t.push(`The previous provider${r}.`),t.push(""),e.stepHistory.length>0){t.push("### Progress Timeline"),t.push("| Step | Label | Scenarios | Components | Functions | Files Changed |"),t.push("|------|-------|-----------|------------|-----------|---------------|");for(const o of e.stepHistory)t.push(`| ${o.step} | ${o.label} | ${o.scenarioCount} | ${o.glossaryComponentCount} | ${o.glossaryFunctionCount} | ${o.uncommittedFileCount} |`);t.push("")}e.handoffSummary&&(t.push("### Previous Provider's Notes"),t.push(`> ${e.handoffSummary}`),t.push(""));const{files:s}=e.uncommittedChanges;if(s.length>0){t.push(`### Uncommitted Changes (${s.length} files)`);const o=s.slice(0,ya);for(const a of o)t.push(`- \`${a.path}\` (${a.status})`);s.length>ya&&t.push(`- ... and ${s.length-ya} more`),t.push("")}return t.push("### Instructions"),t.push("1. Review the uncommitted changes and the progress above"),t.push("2. Run `codeyam editor steps` to see the full step workflow"),e.lastStep&&e.lastStepLabel?t.push(`3. Continue from Step ${e.lastStep} (${e.lastStepLabel}), picking up where ${xa(e.previousProvider)} left off`):t.push("3. Continue where the previous provider left off"),t.push("4. If anything looks wrong, fix it before proceeding"),t.push(""),t.join(`
|
|
474
|
+
`)}async function A1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ce()||process.cwd(),s=G.join(r,".codeyam","config.json");if(!q.existsSync(s))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const o=JSON.parse(q.readFileSync(s,"utf8")),a=o.provider||"claude",i=o.handoff||null;if(t.action==="generate"){const l=kc({projectRoot:r,previousProvider:(i==null?void 0:i.lastProvider)||"unknown",newProvider:a,handoff:i}),c=Ec(l);return new Response(JSON.stringify({context:l,markdown:c}),{headers:{"Content-Type":"application/json"}})}if(t.action==="accept"){const l=kc({projectRoot:r,previousProvider:(i==null?void 0:i.lastProvider)||"unknown",newProvider:a,handoff:i}),c=Ec(l);q.writeFileSync(G.join(r,".codeyam","handoff-context.md"),c,"utf8"),o.handoff={...o.handoff,lastProvider:a,lastUpdated:new Date().toISOString()},q.writeFileSync(s,JSON.stringify(o,null,2),"utf8");try{q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,context:l}),{headers:{"Content-Type":"application/json"}})}return t.action==="dismiss"?(o.handoff={...o.handoff,lastProvider:a,lastUpdated:new Date().toISOString(),stepHistory:[]},q.writeFileSync(s,JSON.stringify(o,null,2),"utf8"),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const T1=Object.freeze(Object.defineProperty({__proto__:null,action:A1},Symbol.toStringTag,{value:"Module"}));async function M1({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),o=G.join(s,".codeyam","journal","index.json");let a={entries:[]};try{const l=await Pe.readFile(o,"utf8");a=JSON.parse(l)}catch{}let i=a.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const $1=Object.freeze(Object.defineProperty({__proto__:null,loader:M1},Symbol.toStringTag,{value:"Module"}));function yp(e){if(!q.existsSync(e))return st.Unknown;try{const t=JSON.parse(q.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?st.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?st.Remix:r["react-scripts"]?st.CRA:r.expo?st.Expo:r.vite?st.Vite:st.Unknown}catch{return st.Unknown}}function F1(e,t){let r=e;const s=G.resolve(t);for(;;){const o=G.resolve(r);if(q.existsSync(G.join(o,"pnpm-lock.yaml")))return"pnpm";if(q.existsSync(G.join(o,"yarn.lock")))return"yarn";if(q.existsSync(G.join(o,"package-lock.json")))return"npm";if(o===s)break;const a=G.dirname(o);if(a===o)break;r=a}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function R1(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function D1(e){const t=G.join(e,"package.json");if(!q.existsSync(t))return{isWebApp:!1};if(yp(t)===st.Unknown)return{isWebApp:!1};try{const o=JSON.parse(q.readFileSync(t,"utf8")).scripts||{},a=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(o).filter(c=>["dev","start","serve","build"].some(u=>c.includes(u))).filter(c=>a.some(u=>o[c].includes(u)));if(l.length===0)return{isWebApp:!1};for(const c of l){const u=o[c],p=R1(u);if(p){const h=G.join(e,p);if(q.existsSync(h)&&q.statSync(h).isDirectory())return{isWebApp:!0,actualPath:h}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function xp(e,t=e,r=0,s=3){if(r>s)return[];const o=[],a=D1(t);if(a.isWebApp){const l=a.actualPath||t,c=G.relative(e,l);return o.push(c||"."),o}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=q.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const u=G.join(t,c.name);o.push(...xp(e,u,r+1,s))}}catch{}return o}function I1(e){const t=xp(e);return t.length===0?[]:t.map(s=>{const o=G.join(e,s),a=G.join(o,"package.json"),i=yp(a),l=F1(o,e);let c;if(i===st.Remix||i===st.Next||i===st.Expo){const m=G.join(o,"app");q.existsSync(m)&&q.statSync(m).isDirectory()&&(c="app")}const u=O1(s,e),h=u?{command:"sh",args:["-c",`${l} run ${u} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:h}})}function O1(e,t){const r=G.join(t,e),s=G.join(r,"package.json");if(!q.existsSync(s))return null;try{const a=JSON.parse(q.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(a[l])return l;return null}catch{return null}}function L1(e,t){const r=new Set(e.map(o=>o.path)),s=[...e];for(const o of t)r.has(o.path)||s.push(o);return s}async function z1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=I1(t)}catch{}if(de.existsSync(r)){const i=JSON.parse(de.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=L1(s,l),s=i.webapps,de.writeFileSync(r,JSON.stringify(i,null,2))}const o=await Ye();if(o)try{await or({projectSlug:o,metadataUpdate:{webapps:s}})}catch{}let a=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",c=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(c.status==="stopped"||c.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),a=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:a,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const B1=Object.freeze(Object.defineProperty({__proto__:null,action:z1},Symbol.toStringTag,{value:"Module"})),Y1=[{id:"plan-project-name",label:"Define project name and description",completed:!1,autoDetect:"project-title-exists"},{id:"plan-tech-stack",label:"Review tech stack",completed:!1,autoDetect:"tech-stack-configured"},{id:"plan-design-system",label:"Create design system",completed:!1,autoDetect:"design-system-exists"},{id:"plan-screen-sizes",label:"Configure screen sizes",completed:!1,autoDetect:"screen-sizes-configured"},{id:"plan-github",label:"Setup GitHub repository",completed:!1,autoDetect:"github-configured"}],U1=[{id:"deploy-hosting",label:"Set up hosting provider",completed:!1,autoDetect:"hosting-configured"},{id:"deploy-env-vars",label:"Configure environment variables",completed:!1,autoDetect:"env-vars-configured"},{id:"deploy-cicd",label:"Set up CI/CD pipeline",completed:!1},{id:"deploy-domain",label:"Configure custom domain",completed:!1},{id:"deploy-production",label:"Deploy to production",completed:!1}];function bp(){return{plan:Y1.map(e=>({...e})),deploy:U1.map(e=>({...e}))}}const Yi=["databases","services","infrastructure"];function vp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function W1(e){try{const t=ee.join(e,".codeyam","config.json"),s=JSON.parse(de.readFileSync(t,"utf8")).techStack;if(!s||typeof s!="object")return[];const o=[];for(const a of Yi){const i=s[a];if(Array.isArray(i))for(const l of i){if(!l.envKeys||!Array.isArray(l.envKeys)||l.envKeys.length===0)continue;const c=vp(l.name);o.push({id:`deploy-svc-${c}`,label:`Set up ${l.name}`,completed:!1,autoDetect:`svc-envkeys-${c}`,serviceRef:{name:l.name,category:a}})}}return o}catch{return[]}}function wp(e){return ee.join(e,".codeyam","roadmap.json")}function Np(e){let t;try{const s=de.readFileSync(wp(e),"utf8");t=V1(JSON.parse(s))}catch{t=bp()}const r=W1(e);return r.length>0&&(t.deploy=J1(t.deploy,r)),t}function J1(e,t){const r=new Set(t.map(u=>u.id)),s=new Set(e.map(u=>u.id)),o=e.filter(u=>!u.id.startsWith("deploy-svc-")||r.has(u.id)),a=o.findIndex(u=>u.id==="deploy-hosting"),i=a>=0?a+1:0,l=t.filter(u=>!s.has(u.id));l.length>0&&o.splice(i,0,...l);const c=new Map(t.map(u=>[u.id,u]));return o.map(u=>{const p=c.get(u.id);return p&&!u.serviceRef?{...u,serviceRef:p.serviceRef,autoDetect:p.autoDetect}:u})}function H1(e,t){const r=wp(e),s=ee.dirname(r);de.existsSync(s)||de.mkdirSync(s,{recursive:!0}),de.writeFileSync(r,JSON.stringify(t,null,2))}function _c(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||typeof t.label!="string"?null:{id:t.id,label:t.label,completed:t.completed===!0,...typeof t.completedAt=="string"?{completedAt:t.completedAt}:{},...typeof t.autoDetect=="string"?{autoDetect:t.autoDetect}:{},...t.userCreated===!0?{userCreated:!0}:{},...t.serviceRef&&typeof t.serviceRef=="object"&&typeof t.serviceRef.name=="string"&&typeof t.serviceRef.category=="string"?{serviceRef:{name:t.serviceRef.name,category:t.serviceRef.category}}:{}}}function jc(e,t){const r=new Set(e.map(a=>a.id)),s=t.filter(a=>!r.has(a.id));if(s.length===0)return e;const o=[...e];for(const a of s){const i=t.indexOf(a),l=t[i-1];if(l){const c=o.findIndex(u=>u.id===l.id);o.splice(c+1,0,{...a})}else o.unshift({...a})}return o}function Pc(e,t){const r=new Map(t.map(s=>[s.id,s]));return e.map(s=>{const o=r.get(s.id);return o!=null&&o.autoDetect&&!s.autoDetect?{...s,autoDetect:o.autoDetect}:s})}function V1(e){const t=bp();if(typeof e!="object"||e===null)return t;const r=e,s=Pc(Array.isArray(r.plan)?jc(r.plan.map(_c).filter(Boolean),t.plan):t.plan,t.plan),o=Pc(Array.isArray(r.deploy)?jc(r.deploy.map(_c).filter(Boolean),t.deploy):t.deploy,t.deploy);return{plan:s,deploy:o}}const K1={"project-title-exists":e=>{try{const t=ee.join(e,".codeyam","config.json");return!!JSON.parse(de.readFileSync(t,"utf8")).projectTitle}catch{return!1}},"tech-stack-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(de.readFileSync(t,"utf8"));return r.techStack&&typeof r.techStack=="object"&&Object.values(r.techStack).some(o=>Array.isArray(o)&&o.length>0)?!0:Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"webapps-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(de.readFileSync(t,"utf8"));return Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"design-system-exists":e=>de.existsSync(ee.join(e,".codeyam","design-system.md")),"screen-sizes-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(de.readFileSync(t,"utf8"));return r.screenSizes!=null&&Object.keys(r.screenSizes).length>0}catch{return!1}},"github-configured":e=>{try{return de.existsSync(ee.join(e,".git"))?Me("git remote get-url origin",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().includes("github.com"):!1}catch{return!1}},"hosting-configured":e=>{var t;try{const r=ee.join(e,".codeyam","config.json"),s=JSON.parse(de.readFileSync(r,"utf8"));return(t=s.hosting)!=null&&t.provider?s.hosting.provider==="vercel"?!!s.hosting.vercelProjectId:!0:!1}catch{return!1}},"scenarios-exist":e=>{const t=ee.join(e,".codeyam","editor-scenarios");try{return de.readdirSync(t).some(s=>s.endsWith(".json"))}catch{return!1}},"env-vars-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(de.readFileSync(t,"utf8")),s=G1(r.techStack);if(s.length===0)return!0;const o=Sp(r.environmentVariables);return s.every(a=>o.has(a))}catch{return!1}}};function G1(e){if(!e||typeof e!="object")return[];const t=[];for(const r of Yi){const s=e[r];if(Array.isArray(s))for(const o of s)o.envKeys&&Array.isArray(o.envKeys)&&t.push(...o.envKeys)}return t}function Sp(e){const t=new Set;if(!Array.isArray(e))return t;for(const r of e){const s=r.key||r.name;s&&r.value&&t.add(s)}return t}function q1(e,t){try{const r=t.replace("svc-envkeys-",""),s=ee.join(e,".codeyam","config.json"),o=JSON.parse(de.readFileSync(s,"utf8")),a=o.techStack;if(!a)return!1;for(const i of Yi){const l=a[i];if(Array.isArray(l)){for(const c of l)if(vp(c.name)===r){if(!c.envKeys||!Array.isArray(c.envKeys)||c.envKeys.length===0)return!1;const u=Sp(o.environmentVariables);return c.envKeys.every(p=>u.has(p))}}}return!1}catch{return!1}}function Ac(e,t){return t.map(r=>{if(!r.autoDetect)return r;let s;const o=K1[r.autoDetect];if(o)s=o(e);else if(r.autoDetect.startsWith("svc-envkeys-"))s=q1(e,r.autoDetect);else return r;if(s&&!r.completed)return{...r,completed:!0,completedAt:new Date().toISOString()};if(!s&&r.completed&&!r.userCreated){const{completedAt:a,...i}=r;return{...i,completed:!1}}return r})}function Q1(e){try{const t=ee.join(e,".codeyam","journal","index.json"),r=de.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.entries)?s.entries.length:0}catch{return 0}}function Z1(e,t=3){try{const r=ee.join(e,".codeyam","journal","index.json"),s=de.readFileSync(r,"utf8"),o=JSON.parse(s);return Array.isArray(o.entries)?o.entries.slice().reverse().slice(0,t).map(a=>({title:a.title,time:a.time,type:a.type||"feature"})):[]}catch{return[]}}function X1(){try{const e=Ce()||process.cwd(),t=Np(e),r=Ac(e,t.plan),s=Ac(e,t.deploy),o=Q1(e),a=Z1(e,3),i=$o(e),l=$i(e);let c=null,u=null,p=[],h=null,m=null,f=null,y=null,g=null,x=null,b=null,v=[];try{const N=ee.join(e,".codeyam","config.json"),w=JSON.parse(de.readFileSync(N,"utf8"));c=w.projectTitle||null,u=w.projectDescription||null,Array.isArray(w.webapps)&&(p=w.webapps.map(C=>({path:C.path||".",framework:C.framework||"Unknown"}))),w.techStack&&typeof w.techStack=="object"&&(h=w.techStack),w.screenSizes&&typeof w.screenSizes=="object"&&(m=w.screenSizes),w.projectScreenSizes&&typeof w.projectScreenSizes=="object"&&(f=w.projectScreenSizes),y=w.defaultScreenSize||null,w.hosting&&typeof w.hosting=="object"&&(g=w.hosting),w.github&&typeof w.github=="object"&&(x=w.github),Array.isArray(w.appFormats)&&(b=w.appFormats),Array.isArray(w.environmentVariables)&&(v=w.environmentVariables)}catch{}return b||(b=Fi(e)),Response.json({plan:r,deploy:s,buildSessionCount:o,recentEntries:a,featureName:i,editorStep:(l==null?void 0:l.step)??null,editorStepLabel:(l==null?void 0:l.label)??null,projectTitle:c,projectDescription:u,webapps:p,techStack:h,screenSizes:m,projectScreenSizes:f,defaultScreenSize:y,appFormats:b,hosting:g,github:x,environmentVariables:v})}catch{return Response.json({plan:[],deploy:[],buildSessionCount:0,recentEntries:[],featureName:null,editorStep:null,editorStepLabel:null,projectTitle:null,projectDescription:null,webapps:[],techStack:null,screenSizes:null,projectScreenSizes:null,defaultScreenSize:null,appFormats:null,hosting:null,github:null,environmentVariables:[]})}}async function eS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await e.json(),s=Np(t);return Array.isArray(r.plan)&&(s.plan=r.plan),Array.isArray(r.deploy)&&(s.deploy=r.deploy),H1(t,s),Nt.notifyChange("unknown"),Response.json({success:!0,...s})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const tS=Object.freeze(Object.defineProperty({__proto__:null,action:eS,loader:X1},Symbol.toStringTag,{value:"Module"}));async function nS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ce()||process.cwd();if(t.action==="clear"){Ty(r);try{q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}try{q.unlinkSync(G.join(r,".codeyam","handoff-context.md"))}catch{}return new Response(JSON.stringify({success:!0,message:"Editor state cleared"}),{headers:{"Content-Type":"application/json"}})}if(t.action==="clear-session-id"){try{q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,message:"Session ID cleared"}),{headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const rS=Object.freeze(Object.defineProperty({__proto__:null,action:nS},Symbol.toStringTag,{value:"Module"}));function $n(){const e=process.memoryUsage(),t=Im.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(Pa.totalmem()/1024/1024),freeMemory:Math.round(Pa.freemem()/1024/1024)}}}function sS(){const e=$n();console.log(`
|
|
475
|
+
[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 oS(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=$n();global.gc();const t=$n(),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 aS(){const e=$n(),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},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function iS({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 s=oS(),o=$n();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:o})}case"detailed":{const s=sS();return Response.json({success:!0,stats:s})}case"leaks":{const s=aS(),o=$n();return Response.json({success:!0,leakCheck:s,stats:o})}default:{const s=$n();return Response.json({success:!0,stats:s,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(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const lS=Object.freeze(Object.defineProperty({__proto__:null,loader:iS},Symbol.toStringTag,{value:"Module"})),js=ti(ei);async function cS({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const o=await Promise.all(s.map(async a=>{const i=dS(a),l=i?await uS(a):null;return{pid:a,isRunning:i,processName:l}}));return Response.json({processes:o})}function dS(e){try{return process.kill(e,0),!0}catch{return!1}}async function uS(e){if(process.platform==="win32")try{const{stdout:r}=await js(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const o=s[1];if(o.toLowerCase()==="node.exe")try{const{stdout:a}=await js(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=a.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return o}catch{return null}try{const{stdout:r}=await js(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await js(`ps -p ${e} -o args=`),o=s.trim(),a=o.match(/codeyam-(\w+)/);return a?`codeyam-${a[1]}`:o.split(" ")[0]||null}catch{return null}}}const pS=Object.freeze(Object.defineProperty({__proto__:null,loader:cS},Symbol.toStringTag,{value:"Module"})),hS=lo(import.meta.url),mS=G.dirname(hS);function fS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=wo(),r=Ce()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,o=G.join(mS,"..","..","..","..","webserver","bootstrap.js"),a=G.join(r,".codeyam","logs");q.existsSync(a)||q.mkdirSync(a,{recursive:!0});const i=q.openSync(G.join(a,"background-server.log"),"a"),l=q.openSync(G.join(a,"background-server-error.log"),"a"),c=new Date().toISOString();q.appendFileSync(G.join(a,"background-server.log"),`
|
|
476
|
+
[${c}] Server restart requested via dashboard
|
|
477
|
+
`),fi();const u=kt("node",[o],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});u.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${u.pid})`);const p=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),p}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 gS=Object.freeze(Object.defineProperty({__proto__:null,action:fS},Symbol.toStringTag,{value:"Module"}));async function yS({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)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 ${s.length} scenarios to save`),s.forEach((l,c)=>{var h,m,f,y,g;const u=(m=(h=l.metadata)==null?void 0:h.data)==null?void 0:m.argumentsData,p=Array.isArray(u)&&u.length>0?JSON.stringify(u[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(u)?u.length:"not-array",argumentsDataPreview:p})});const o=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),a=await _g(o);if(!a||a.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 ${a.length} scenarios to database`),a.forEach((l,c)=>{var p,h;const u=(h=(p=l.metadata)==null?void 0:p.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(u)?u.length:"not-array"})});const i={...r,scenarios:a};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 xS=Object.freeze(Object.defineProperty({__proto__:null,action:yS},Symbol.toStringTag,{value:"Module"})),bS=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function vS({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",o=new URLSearchParams;r&&o.set("search",r),s!=="1"&&o.set("page",s);const a=o.toString(),i=new URL(`/api/agent-transcripts${a?`?${a}`:""}`,e.url),c=await(await fetch(i.toString())).json();if(c.error)return le({agents:[],error:c.error,search:r,page:1,totalPages:1});const u=c.total??(c.agents||[]).length,p=c.pageSize??20;return le({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(u/p))})}catch(t){return console.error("Failed to load agent transcripts:",t),le({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function wS(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 NS(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 SS(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function Bs({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"},s={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:s[e]||e})}function CS({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),d("div",{children:[d("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function kS({content:e,truncated:t,fullLength:r}){const[s,o]=P(!1);return d("div",{children:[d("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>o(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function ES({entry:e,pairedResult:t}){const[r,s]=P(!1),o=wS(e.timestamp||"");return e.type==="user_prompt"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Bs,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:o})]}),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"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Bs,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:o})]}),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"?d("div",{className:"my-2",children:[d("button",{onClick:()=>s(!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(At,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(yn,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Bs,{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:o})]}),r&&d("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(CS,{input:e.input||{}}),t&&d("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[d("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(kS,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function _S({context:e}){const[t,r]=P(!1);return d("div",{className:"my-2",children:[d("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(At,{className:"w-3 h-3 text-gray-400"}):n(yn,{className:"w-3 h-3 text-gray-400"}),n(Bs,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function jS({snippet:e}){const[t,r]=P(!1),s=e.split(`
|
|
478
|
+
`).filter(l=>l.trim()),o=s.slice(0,4),a=s.length>4,i=t?s:o;return d("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n(rm,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,c)=>{const u=l.match(/^\[(\w+)\]:\s*(.*)/);if(!u)return null;const[,p,h]=u,m=p==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${m?"text-blue-700":"text-gray-500"}`,children:[m?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},c)})}),a&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function PS({change:e}){const[t,r]=P(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return d("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:d("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(At,{className:"w-3 h-3 inline flex-shrink-0"}):n(yn,{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"&&d("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&d("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&&d("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 AS({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),o=r.some(i=>i.action==="modified");return d("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":o?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),d("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(PS,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function TS({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",o=t?"text-red-700":"text-green-700",a=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",a]}),d("div",{className:`text-xs ${o} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((c,u)=>n("div",{className:"text-red-700 break-words",children:c},u))})]})]})}function MS({agent:e,defaultOpen:t,isAdmin:r}){var C,S,k;const[s,o]=P(t),[a,i]=P(!1),[l,c]=P(null),[u,p]=P(!1),h=pe(()=>{const T={};for(const _ of e.entries)_.type==="tool_result"&&_.tool_use_id&&(T[_.tool_use_id]=_);return T},[e.entries]),m=pe(()=>{const T=new Set;for(const _ of e.entries)_.type==="tool_call"&&_.tool_use_id&&h[_.tool_use_id]&&T.add(_.tool_use_id);return T},[e.entries,h]),f=T=>{T.stopPropagation(),i(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(_=>_.json()).then(_=>{_.success?c(`Saved to ${_.fixturePath}`):c(`Error: ${_.error}`)}).catch(_=>{c(`Error: ${_ instanceof Error?_.message:String(_)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(T=>T.action!=="touched"),g=y.filter(T=>T.action==="created"),x=y.filter(T=>T.action==="modified"),b=(e.ruleChanges||[]).filter(T=>T.action==="touched"),v=y.length>0,N=b.length>0,w=v||N;return d("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[d("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(At,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(yn,{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}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:SS(e.model)}),g.length>0&&d("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(Js,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&d("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(Js,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!v&&N&&d("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:[b.length," timestamp",b.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(Ws,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),d("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((C=e.sessionResult)==null?void 0:C.duration_ms)!=null&&d(ve,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((S=e.sessionResult)==null?void 0:S.total_cost_usd)!=null&&d(ve,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),d("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[NS(e.timestamp),r&&v&&d("button",{onClick:f,disabled:a,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(nm,{className:"w-3 h-3"}),a?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&d("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&d("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:T=>{T.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),p(!0),setTimeout(()=>p(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:u?n(Mt,{className:"w-3.5 h-3.5 text-green-500"}):n(Ot,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(TS,{result:e.sessionResult}),e.stats.errors>0&&((k=e.stats.errorMessages)==null?void 0:k.length)>0&&d("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[d("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((T,_)=>n("li",{className:"break-words",children:T},_))})]}),e.conversationSnippet&&n(jS,{snippet:e.conversationSnippet}),w&&n(AS,{changes:e.ruleChanges}),e.context&&n(_S,{context:e.context}),e.entries.map((T,_)=>{if(T.type==="tool_result"&&T.tool_use_id&&m.has(T.tool_use_id))return null;const $=T.type==="tool_call"&&T.tool_use_id?h[T.tool_use_id]:void 0;return n(ES,{entry:T,pairedResult:$},`${e.id}-${_}`)})]})]})}function ba(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const $S=nt(function(){const{agents:t,error:r,search:s,page:o,totalPages:a}=lt(),i=zt(),l=Cd("root"),c=(l==null?void 0:l.isAdmin)??!1,[u,p]=P(s),[h,m]=P(!1),[f,y]=P(0);Yt({source:"agent-transcripts-page"});const g=b=>{b.preventDefault(),window.location.href=ba(1,u)},x=()=>{m(!h),y(b=>b+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[d("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(em,{className:"w-5 h-5"})}),n(Hs,{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"})]}),d("div",{className:"flex items-center gap-4 mb-6",children:[d("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:u,onChange:b=>p(b.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:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",o," of ",a,s&&d("span",{children:[" ","matching “",s,"”",n(ke,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Hs,{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(b=>n(MS,{agent:b,defaultOpen:h,isAdmin:c},b.id))},f),a>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:o>1?ba(o-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${o>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(tm,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[o," / ",a]}),d("a",{href:o<a?ba(o+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${o<a?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(yn,{className:"w-4 h-4"})]})]})]})})}),FS=Object.freeze(Object.defineProperty({__proto__:null,default:$S,loader:vS,meta:bS},Symbol.toStringTag,{value:"Module"}));async function RS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const o=wN(s);o&&console.log("[editor-commit] Initialized new git repository"),NN(s),console.log("[editor-commit] Staged all changes");const a=SN(s,r);console.log(`[editor-commit] Created commit: ${a}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>sb);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:a,initialized:o}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const DS=Object.freeze(Object.defineProperty({__proto__:null,action:RS},Symbol.toStringTag,{value:"Module"}));function IS(){const e={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const t=Ce()||process.cwd(),r=G.join(t,".codeyam","data-structure.json");if(q.existsSync(r))try{const a=JSON.parse(q.readFileSync(r,"utf-8")),i=Array.isArray(a)?a:[];return i.sort((l,c)=>(l.order??99)-(c.order??99)),new Response(JSON.stringify({dataStructures:i,source:"explicit"}),{headers:e})}catch{}const s=G.join(t,"prisma","schema.prisma");if(q.existsSync(s)){const a=q.readFileSync(s,"utf-8"),i=OS(a);return new Response(JSON.stringify({models:i,source:"prisma"}),{headers:e})}const o=LS(t);return o.length>0?new Response(JSON.stringify({models:o,source:"typescript"}),{headers:e}):new Response(JSON.stringify({models:[],source:null}),{headers:e})}catch{return new Response(JSON.stringify({models:[],source:null}),{headers:e})}}function OS(e){const t=[],r=/model\s+(\w+)\s*\{([^}]+)\}/g,s=new Set;let o;const a=/model\s+(\w+)\s*\{/g;for(;(o=a.exec(e))!==null;)s.add(o[1]);let i;for(;(i=r.exec(e))!==null;){const l=i[1],c=i[2],u=[];for(const p of c.split(`
|
|
479
|
+
`)){const h=p.trim();if(!h||h.startsWith("//")||h.startsWith("@@"))continue;const m=h.match(/^(\w+)\s+([\w[\]?]+)\??(\s+.*)?$/);if(!m)continue;const f=m[1];let y=m[2];const g=m[3]||"",x=y.endsWith("[]"),b=y.endsWith("?")||h.includes("?");y=y.replace(/[[\]?]/g,"");const v=s.has(y),N=g.includes("@id");u.push({name:f,type:y,isRelation:v,isOptional:b,isList:x,isId:N,...v?{relatedModel:y}:{}})}t.push({name:l,fields:u})}return t}function LS(e){const t=G.join(e,"src");if(!q.existsSync(t))return[];const r=[],s=new Set,o=[],a=["src","src/lib","src/types","src/utils","src/models"];for(const i of a){const l=G.join(e,i);if(q.existsSync(l))try{for(const c of q.readdirSync(l))c.endsWith(".ts")&&!c.endsWith(".test.ts")&&!c.endsWith(".spec.ts")&&o.push(G.join(l,c))}catch{}}for(const i of o){const l=q.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)/g;let u;for(;(u=c.exec(l))!==null;)s.add(u[1])}for(const i of o){const l=q.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)\s*\{([^}]+)\}/g;let u;for(;(u=c.exec(l))!==null;){const p=u[1],h=u[2],m=[];for(const f of h.split(`
|
|
480
|
+
`)){const y=f.trim();if(!y||y.startsWith("//"))continue;const g=y.match(/^(\w+)(\?)?:\s*([^;/]+)/);if(!g)continue;const x=g[1],b=!!g[2];let v=g[3].trim();const N=v.endsWith("[]");v=v.replace(/\[\]$/,"");const w=s.has(v);m.push({name:x,type:v,isRelation:w,isOptional:b,isList:N,isId:x==="id",...w?{relatedModel:v}:{}})}r.push({name:p,fields:m})}}return r}const zS=Object.freeze(Object.defineProperty({__proto__:null,loader:IS},Symbol.toStringTag,{value:"Module"}));async function BS({request:e}){const r=new URL(e.url).searchParams.get("skipTests")==="true",s=Ce()||process.cwd(),o=G.join(s,".codeyam","glossary.json");let a;try{const O=q.readFileSync(o,"utf8");a=Co(JSON.parse(O))}catch{return Response.json(ua({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}))}if(a.length===0)return Response.json(ua({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}));const i=G.join(s,".codeyam","editor-step.json");let l=null;try{const O=q.readFileSync(i,"utf8");l=JSON.parse(O).featureStartedAt||null}catch{}let c,u=[];const p=await Ye();if(p)try{const{project:O}=await De(p),W=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",O.id).orderBy("created_at","asc").execute(),J=Tt(W,A=>`${A.name}::${A.url||"/"}`),j=J.map(A=>({componentName:A.component_name||null,componentPath:A.component_path||null,pageFilePath:A.page_file_path??null,url:A.url??null,displayName:A.display_name??null}));u=J.map(A=>({name:A.name,componentName:A.component_name||null,pageFilePath:A.page_file_path??null,url:A.url??null}));const D=await yr({projectRoot:s,scenarioInputs:j});Object.keys(D.entityChangeStatus).length>0&&(c=D.entityChangeStatus)}catch{}const h=Yb({featureStartedAt:l,entityChangeStatus:c});l=h.featureStartedAt,c=h.entityChangeStatus;const m=Ub(a,c),{components:f,functions:y}=Bb(m);let g={},x={};if(p)try{const{project:O}=await De(p),U=$e();g=await lc(U,O.id,l);const W=await cc(U,O.id,l);for(const[J,j]of Object.entries(W)){const D=m.find(A=>A.filePath===J);D&&(g[D.name]=(g[D.name]||0)+j)}if(l&&c){const J=await lc(U,O.id,null),j=await cc(U,O.id,null);x={...J};for(const[D,A]of Object.entries(j)){const L=m.find(E=>E.filePath===D);L&&(x[L.name]=(x[L.name]||0)+A)}}}catch{}let b={};try{const O=process.env.CODEYAM_ROOT_PATH||process.cwd(),U=await Wu(O);b=Kb(U,u)}catch{}const v={};for(const O of y)O.testFile&&(v[O.testFile]=q.existsSync(G.join(s,O.testFile)));const N={},w={};if(!r){const O=y.filter(W=>W.testFile&&v[W.testFile]).map(W=>W.testFile),U=[...new Set(O)];if(U.length>0){const W=Li(s),J=y.filter(E=>!!E.testFile&&v[E.testFile]).map(E=>({filePath:E.filePath,testFile:E.testFile})),j=zi(s,J),D=new Set(c?Object.entries(c).filter(([,E])=>E.status==="impacted").map(([E])=>E):[]),A=[],L={};for(const E of U){const F=W.results[E],I=j[E],K=y.some(Q=>Q.testFile===E&&D.has(Q.name));F&&I&&!lp(F,I.sourceHash,I.testHash)&&!K?L[E]={testFilePath:F.testFilePath,status:F.status,testCases:F.testCases,...F.errorMessage?{errorMessage:F.errorMessage}:{}}:A.push(E)}try{const E=A.length>0?await rN(s,A):{},F={...L,...E};try{dp(s,E,J)}catch{}for(const I of y){if(!I.testFile||!v[I.testFile])continue;const K=F[I.testFile];if(!K)continue;const Q=K.status==="passed",V=K.testCases.some(Y=>Y.fullName.startsWith(I.name));w[I.name]=K.testCases.filter(Y=>Y.fullName.startsWith(I.name)&&Y.status!=="skipped").length,N[I.testFile]={passing:Q,hasEntityNameDescribe:V,...K.status==="error"&&K.errorMessage?{errorMessage:K.errorMessage}:{}}}}catch(E){for(const F of U)N[F]={passing:!1,hasEntityNameDescribe:!1,errorMessage:E.message||"Unknown test runner error"}}}}const C=new Set(a.map(O=>O.filePath)),S=[];if(p)try{const{project:O}=await De(p),W=await $e().selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path"]).where("project_id","=",O.id).execute(),J=new Map;for(const j of W){const D=j,A=D.component_path||D.page_file_path;if(!A)continue;const L=J.get(A);L?L.count++:J.set(A,{name:D.component_name||G.basename(A,G.extname(A)),count:1})}for(const[j,D]of J)C.has(j)||S.push({name:D.name,filePath:j,scenarioCount:D.count})}catch{}const k=ua({components:f,functions:y,scenarioCounts:g,testFileExistence:v,testResults:N,clientErrors:b,totalScenarioCounts:x,entityChangeStatus:c,testCaseCounts:w});k.missingFromGlossary=S,S.length>0&&(k.summary.allPassing=!1,k.summary.missingFromGlossary=S.length);let T=[];if(p)try{const{project:O}=await De(p),U=$e();T=await Wb(U,O.id,l)}catch{}if(k.incompleteEntities=T,T.length>0){k.summary.allPassing=!1,k.summary.incompleteEntities=T.length;const O=T.filter(U=>U.preExisting).length;O>0&&(k.summary.preExistingIncompleteEntities=O)}let _=[];if(p)try{const{project:O}=await De(p),U=$e();_=await Jb(U,O.id,l)}catch{}k.miscategorizedScenarios=_,_.length>0&&(k.summary.allPassing=!1,k.summary.miscategorizedScenarios=_.length);let $=[];if(p)try{const{project:O}=await De(p),U=$e();$=await Hb(U,O.id,l)}catch{}k.unassociatedScenarios=$,$.length>0&&(k.summary.allPassing=!1,k.summary.unassociatedScenarios=$.length);let M=[];if(p&&c&&Object.keys(c).length>0)try{const{project:O}=await De(p),W=await $e().selectFrom("editor_scenarios").select(["editor_scenarios.name","editor_scenarios.component_name","editor_scenarios.page_file_path","editor_scenarios.url","editor_scenarios.created_at","editor_scenarios.updated_at"]).where("editor_scenarios.project_id","=",O.id).execute(),J=l?Xr(l):null,j=W.map(D=>({name:D.name,entityName:tn({componentName:D.component_name,pageFilePath:D.page_file_path,url:D.url}),updatedInSession:J?xi({created_at:D.created_at,updated_at:D.updated_at},J):!1}));M=Zu({scenarios:j,entityChangeStatus:c})}catch{}k.scenariosNeedingRecapture=M,M.length>0&&(k.summary.allPassing=!1,k.summary.scenariosNeedingRecapture=M.length);const R=[],z=Vb(a);for(const[O,U]of z)R.push({name:O,filePaths:U.map(W=>W.filePath)});return k.duplicateNames=R,Response.json(k)}const YS=Object.freeze(Object.defineProperty({__proto__:null,loader:BS},Symbol.toStringTag,{value:"Module"}));async function US({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:o}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Tc(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(p){return Response.json({error:"Failed to kill process",pid:r,details:p instanceof Error?p.message:String(p)},{status:500})}const i=3e4,l=500,c=Date.now();let u=!0;for(;u&&Date.now()-c<i;)await new Promise(p=>setTimeout(p,l)),u=Tc(r);if(u){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(p=>setTimeout(p,2e3))}catch(p){console.error(`Failed to SIGKILL process ${r}:`,p)}}if(o)try{await pn({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(p){console.error("Failed to update database after killing process:",p)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-c})}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 Tc(e){try{return process.kill(e,0),!0}catch{return!1}}const WS=Object.freeze(Object.defineProperty({__proto__:null,action:US},Symbol.toStringTag,{value:"Module"})),JS=lo(import.meta.url),HS=ee.dirname(JS),VS=ee.resolve(HS,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function KS(e){const t=[],r=new Set;for(const s of e.split(`
|
|
481
|
+
`)){const o=s.trim();if(!o)continue;let a;try{a=JSON.parse(o)}catch{continue}if(a.type!=="assistant")continue;const i=a.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type!=="tool_use")continue;const u=String(c.name||""),p=c.input||{};if(u==="Write"||u==="Edit"){const h=String(p.file_path||"");if(h.includes(".claude/rules/")){const m=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${u}:${m}`;r.has(f)||(r.add(f),t.push({action:u==="Write"?"created":"modified",filePath:m}))}}else if(u==="Bash"){const h=String(p.command||"");if(h.includes("codeyam memory touch")){const m=`touch:${h}`;r.has(m)||(r.add(m),t.push({action:"touched",filePath:h}))}}}}return t}async function GS({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 s=await pp(),o=s?ee.join(Ls,s):null;let a=o?ee.join(o,`${r}.log`):"";if((!a||!Pt(a))&&(a=ee.join(Ls,`${r}.log`)),!Pt(a))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await ja(a,"utf-8");let l=o?ee.join(o,`${r}.context`):"";(!l||!Pt(l))&&(l=ee.join(Ls,`${r}.context`));let c=null;if(Pt(l))try{c=await ja(l,"utf-8")}catch{}const u=KS(i),h=c?["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(x=>c.toLowerCase().includes(x)):!1,m=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+m,y=ee.join(VS,f);await km(y,{recursive:!0}),await Rr(ee.join(y,"agent-log.jsonl"),i),c&&await Rr(ee.join(y,"context.md"),c),await Rr(ee.join(y,"rule-changes.json"),JSON.stringify(u,null,2)),await Rr(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:u.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}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 qS=Object.freeze(Object.defineProperty({__proto__:null,action:GS},Symbol.toStringTag,{value:"Module"}));async function QS({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=Ce();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await Ae.access(s);const o=await Ae.readFile(s),a=ee.extname(s).toLowerCase(),i=a===".png"?"image/png":a===".jpg"||a===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const ZS=Object.freeze(Object.defineProperty({__proto__:null,loader:QS},Symbol.toStringTag,{value:"Module"})),Mc={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 Ui({type:e,className:t=""}){const r=Mc[e]||Mc.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 XS={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 Ps({variant:e,pid:t,label:r,className:s=""}){const o=XS[e],a=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] ${s}`,style:{backgroundColor:o.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:o.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:a})})}let $c=!1;function eC(){if($c)return;const e=document.createElement("style");e.textContent=`
|
|
482
|
+
@keyframes strongPulse {
|
|
483
|
+
0%, 100% { opacity: 0.2; }
|
|
484
|
+
50% { opacity: 1; }
|
|
485
|
+
}
|
|
486
|
+
`,document.head.appendChild(e),$c=!0}function Wi({size:e="medium",className:t=""}){typeof document<"u"&&eC();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:o,gap:a}=r[e];return d("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${a}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${o}px`,height:`${o}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const tC=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function nC({request:e,context:t,params:r}){var D,A,L,E,F,I,K,Q;let s=t.analysisQueue;s||(s=await en());const o=new URL(e.url),a=parseInt(o.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return le({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:a,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 c=s.getState(),u=await Ye();let p=null;if(u&&((D=c==null?void 0:c.currentlyExecuting)!=null&&D.commitSha)){const{project:V,branch:Y}=await De(u),B=await Qs({projectId:V.id,branchId:Y.id,shas:[c.currentlyExecuting.commitSha]});p=B&&B.length>0?B[0]:null}else p=await hr();const h=async V=>{const Y=await In(V);if(!Y)return null;const{getAnalysesForEntity:B}=await Promise.resolve().then(()=>Gg),H=await B(V,!1);return{...Y,analyses:H||[]}},m=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async V=>{const Y=[];if(V.entityShas&&V.entityShas.length>0){const B=V.entityShas.map(ne=>h(ne)),H=await Promise.all(B);Y.push(...H.filter(ne=>ne!==null))}return{...V,entities:Y}}));let f=null;if(c!=null&&c.currentlyExecuting){const V=c.currentlyExecuting,Y=[];if(V.entityShas&&V.entityShas.length>0){const B=V.entityShas.map(ne=>h(ne)),H=await Promise.all(B);Y.push(...H.filter(ne=>ne!==null))}f={...V,entities:Y}}const y=f?m.filter(V=>V.id!==f.id):m,g=((L=(A=p==null?void 0:p.metadata)==null?void 0:A.currentRun)==null?void 0:L.currentEntityShas)||[],b=(await Promise.all(g.map(V=>h(V)))).filter(V=>V!==null),v=[];if(u)try{const{project:V,branch:Y}=await De(u),B=await Qs({projectId:V.id,branchId:Y.id,limit:100});for(const H of B){const ne=((E=H.metadata)==null?void 0:E.historicalRuns)||[];v.push(...ne)}}catch(V){console.error("[activity.tsx] Failed to load historical runs from commits:",V)}const N=[...v].sort((V,Y)=>{const B=V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt||"";return(Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"").localeCompare(B)}),w=(a-1)*i,C=w+i,S=N.slice(w,C),k=Math.ceil(N.length/i),T=await Promise.all(S.map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{...V,entities:[]};const B=await Promise.all(Y.map(H=>h(H)));return{...V,entities:B.filter(H=>H!==null)}})),_=!!f,$=y.length,M=N.filter(V=>{const Y=!!V.failedAt,B=V.readyToBeCaptured,H=V.capturesCompleted??0,ne=B===void 0?!0:B===0||H>=B;return!Y&&!!V.analysisCompletedAt&&ne}),R=new Set(((F=f==null?void 0:f.entities)==null?void 0:F.map(V=>V.sha))||[]),z=M.filter(V=>!(V.currentEntityShas||[]).some(B=>R.has(B))),U=(await Promise.all(z.slice(0,3).map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{run:V,entities:[]};const B=await Promise.all(Y.map(H=>h(H)));return{run:V,entities:B.filter(H=>H!==null)}}))).flatMap(({run:V,entities:Y})=>Y.map(B=>({...B,runId:V.id,completedAt:V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt})));let W=[],J=null,j=null;if((K=(I=p==null?void 0:p.metadata)==null?void 0:I.currentRun)!=null&&K.analysisCompletedAt&&b.length>0){const V=b[0].sha;J=b[0];const Y=await mo(V);Y&&Y.length>0&&Y[0].scenarios&&(W=Y[0].scenarios,j=Y[0].status)}return le({state:{...c,jobs:y,currentlyExecuting:f},currentRun:(Q=p==null?void 0:p.metadata)==null?void 0:Q.currentRun,historicalRuns:T,totalHistoricalRuns:N.length,currentPage:a,totalPages:k,projectSlug:u,commitSha:p==null?void 0:p.sha,queueJobs:y,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:_,queuedCount:$,recentCompletedEntities:U,hasMoreCompletedRuns:z.length>3,currentEntityScenarios:W,currentEntityForScenarios:J,currentAnalysisStatus:j})}function rC({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const o=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:o.map(a=>{const i=e===a.id;return n(ke,{to:a.id==="current"?"/activity":`/activity/${a.id}`,className:`
|
|
487
|
+
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
488
|
+
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
489
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[a.label,a.count!==null&&a.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:a.count}),a.count===null&&a.hasContent&&n("span",{className:`
|
|
490
|
+
inline-block w-2 h-2 rounded-full
|
|
491
|
+
${i?"":"bg-gray-400"}
|
|
492
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},a.id)})})})}function sC({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:o,onShowLogs:a,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:u,currentAnalysisStatus:p}){var O,U,W,J;const[h,m]=P({}),[f,y]=P({isKilling:!1,current:0,total:0}),g=Bt(),x=!!e,b=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),N=v&&!!(t!=null&&t.capturePid),w=!v,C=x,S=c||[],{lastLine:k}=Qt(s,C);se(()=>{if(!t)return;const j=[t.analyzerPid,t.capturePid].filter(E=>!!E);if(j.length===0)return;let D=!0;const A=async()=>{try{const F=await(await fetch(`/api/process-status?pids=${j.join(",")}`)).json();if(F.processes&&D){const I={};F.processes.forEach(K=>{I[K.pid]={isRunning:K.isRunning,processName:K.processName}}),m(I)}}catch(E){D&&console.error("Failed to fetch process statuses:",E)}};A();const L=setInterval(()=>void A(),5e3);return()=>{D=!1,clearInterval(L)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[T,_]=P(!1),[$,M]=P(!1);se(()=>{b.length<=3&&T&&_(!1)},[b.length,T]),se(()=>{i.length<=3&&$&&M(!1)},[i.length,$]);const R=T?b:b.slice(0,3),z=b.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[C?d("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[d("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(It,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),R.map(j=>d("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:[d("div",{className:"flex items-center gap-3",children:[n("div",{children:n(St,{type:j.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(ke,{to:`/entity/${j.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:j.name}),j.entityType&&n(Ui,{type:j.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:j.filePath,children:j.filePath})]})]}),n("button",{onClick:a,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"})]},j.sha)),z&&!T&&d("button",{onClick:()=>_(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",b.length-3," more"," ",b.length-3===1?"entity":"entities"]}),T&&z&&n("button",{onClick:()=>_(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),N&&S&&S.length>0&&u&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(j=>{var K,Q,V,Y;if(!j.id)return null;const D=(Q=(K=j.metadata)==null?void 0:K.screenshotPaths)==null?void 0:Q[0],A=(V=j.metadata)==null?void 0:V.noScreenshotSaved,L=D&&!A,E=(Y=p==null?void 0:p.scenarios)==null?void 0:Y.find(B=>B.name===j.name),I=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt||!L&&!A;return n(ke,{to:`/entity/${u.sha}/scenarios/${j.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:I?"#f9f9f9":void 0,borderColor:I?"#efefef":"#ccc"},children:L?n(ut,{screenshotPath:D,alt:j.name,className:"w-full h-full object-contain bg-gray-100"}):I?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Wi,{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"})},j.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))&&d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-2",children:[d("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Ps,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((O=h[t.analyzerPid])==null?void 0:O.isRunning))&&n(Ps,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Ps,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||((U=h[t.capturePid])==null?void 0:U.isRunning))&&n(Ps,{variant:"running"})]}),(((W=h[t==null?void 0:t.analyzerPid])==null?void 0:W.isRunning)||((J=h[t==null?void 0:t.capturePid])==null?void 0:J.isRunning))&&n("button",{onClick:()=>{const j=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(L=>{var E;return!!L&&((E=h[L])==null?void 0:E.isRunning)});if(j.length===0)return;const D=j.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${D})?`))return;y({isKilling:!0,current:1,total:j.length}),(async()=>{for(let L=0;L<j.length;L++){const E=j[L];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:E,commitSha:o||""})})}catch(F){console.error(`Failed to kill process ${E}:`,F)}L<j.length-1&&y({isKilling:!0,current:L+2,total:j.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):d("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:[d("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(jd,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),d("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(ke,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(ke,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),d(ke,{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&&d("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"}),d("div",{className:"flex flex-col gap-4",children:[($?i:i.slice(0,3)).map(j=>{var L;const D=(L=j.analyses)==null?void 0:L[0],A=(D==null?void 0:D.scenarios)||[];return D==null||D.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:d("div",{className:"flex flex-col gap-[15px]",children:[d("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(St,{type:j.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[n(ke,{to:`/entity/${j.sha}`,className:"hover:underline cursor-pointer",title:j.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:j.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:j.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:j.filePath,children:j.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:a,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]"}),A.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:A.map(E=>{var Q,V,Y;if(!E.id)return null;const F=(V=(Q=E.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:V[0],I=(Y=E.metadata)==null?void 0:Y.noScreenshotSaved,K=F&&!I;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(ke,{to:`/entity/${j.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:K?"#f3f4f6":"#FAFAFA",borderColor:K?"#d1d5db":"#BCCDD3",borderStyle:K?"solid":"dashed"},onMouseEnter:B=>{K&&(B.currentTarget.style.borderColor="#005C75",B.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:B=>{B.currentTarget.style.borderColor=K?"#d1d5db":"#BCCDD3",B.currentTarget.style.boxShadow="none"},children:K?n(ut,{screenshotPath:F,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"})]})},j.sha)}),i.length>3&&!$&&d("button",{onClick:()=>M(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),$&&i.length>3&&n("button",{onClick:()=>M(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function oC({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return d("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:[d("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(sm,{size:24,style:{color:"#005C75"}})}),d("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."})]})]}),d(ke,{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[s,o]=P(null),[a,i]=P(null),[l,c]=P(null),[u,p]=P(!1),[h,m]=P(!1),[f,y]=P(new Set),g=Bt();se(()=>{e.length<=3&&h&&m(!1)},[e.length,h]);const x=S=>{o(S)},b=(S,k)=>{S.preventDefault(),i(k)},v=async(S,k)=>{if(S.preventDefault(),!s){i(null);return}const T=e.findIndex(M=>M.id===s);if(T===-1){o(null),i(null);return}if(T===k){o(null),i(null);return}const _=T<k?"down":"up",$=Math.abs(k-T);p(!0);try{for(let M=0;M<$;M++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:_})});g.revalidate()}catch(M){console.error("Failed to reorder job:",M)}finally{p(!1),o(null),i(null)}},N=()=>{u||(o(null),i(null))},w=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)}},C=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 d("div",{children:[d("div",{className:"flex items-center justify-between mb-4",children:[d("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 C(),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"})]}),d("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(S=>{var z,O,U,W;const k=e.findIndex(J=>J.id===S.id),T=l===k,_=s===S.id,$=a===k,M=f.has(S.id),R=((z=S.entities)==null?void 0:z.length)>0?M?S.entities:S.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:_||u?.5:1,transform:$&&s!==null&&!_?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:u?"not-allowed":_?"grabbing":"grab"},onMouseEnter:()=>c(k),onMouseLeave:()=>c(null),draggable:!u,onDragStart:J=>{x(S.id),J.dataTransfer.effectAllowed="move"},onDragOver:J=>b(J,k),onDrop:J=>void v(J,k),onDragEnd:N,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(om,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[R.length>0?d(ve,{children:[R.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:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(St,{type:J.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(ke,{to:`/entity/${J.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:J.name}),J.entityType&&n(Ui,{type:J.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:J.filePath})]})]})})},J.sha)),((O=S.entities)==null?void 0:O.length)>3&&n("button",{onClick:()=>{y(J=>{const j=new Set(J);return j.has(S.id)?j.delete(S.id):j.add(S.id),j})},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:M?"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:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Vs,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((U=S.entityNames)==null?void 0:U[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:((W=S.filePaths)==null?void 0:W[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")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[T&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(am,{size:20})}),n("button",{onClick:()=>void w(S.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},S.id)}),e.length>3&&!h&&d("button",{onClick:()=>m(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>m(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function aC({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:o,onShowLogs:a}){if(t===0)return d("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:[d("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(im,{size:24,style:{color:"#005C75"}})}),d("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."})]})]}),d(ke,{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]=P(!1),c=[];e.forEach(p=>{p.entities&&p.entities.length>0&&p.entities.forEach(h=>{c.push({...h,runCreatedAt:p.createdAt})})});const u=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[u.map(p=>{var y;const h=(y=p.analyses)==null?void 0:y[0],m=(h==null?void 0:h.scenarios)||[],f=!p.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(St,{type:p.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(ke,{to:`/entity/${p.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:p.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:p.filePath,children:p.filePath})]})]}),n("button",{onClick:a,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),m.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[m.slice(0,8).map(g=>{var N,w,C;if(!g.id)return null;const x=(w=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:w[0],b=(C=g.metadata)==null?void 0:C.noScreenshotSaved,v=x&&!b;return n(ke,{to:`/entity/${p.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:v?"#ccc":"#BCCDD3",borderStyle:v?"solid":"dashed"},children:v?n(ut,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),m.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",m.length-8," more"]})]})]},`${p.sha}-${p.runCreatedAt}`)}),c.length>3&&!i&&d("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:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.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 iC=nt(function(){const t=lt(),r=kd(),[s,o]=P(!1);Yt({source:"activity-page"});const a=r.tab||"current";return t?d("div",{className:"px-20 py-12",children:[d("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(rC,{activeTab:a,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),a==="current"&&n(sC,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),a==="queued"&&n(oC,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),a==="historic"&&n(aC,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:a,onShowLogs:()=>o(!0)}),s&&t.projectSlug&&n(hn,{projectSlug:t.projectSlug,onClose:()=>o(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),lC=Object.freeze(Object.defineProperty({__proto__:null,default:iC,loader:nC,meta:tC},Symbol.toStringTag,{value:"Module"}));async function Cp(e,t,r){var w,C;await We();const s=await Xt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const o=Ce();if(!o)throw new Error("Project root not found");const a=G.join(o,".codeyam","config.json"),i=JSON.parse(q.readFileSync(a,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=Qr(l);try{q.writeFileSync(c,"","utf8")}catch{}const{project:u}=await De(l),p=((w=u.metadata)==null?void 0:w.packageManager)||"npm",h=3112,m=Lt(l),f=((C=u.metadata)==null?void 0:C.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=lg({filePath:s.filePath,webapps:f,environmentVariables:y,port:h,packageManager:p});await pr(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:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=g.startCommand,v={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:m}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${m}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:m,projectSlug:l,port:h,packageManager:p,framework:g.framework,instructions:v}}async function cC({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),o=r.searchParams.get("scenarioId")||void 0;if(!s)return le({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 a=t.analysisQueue;if(a||(a=await en()),!a)return le({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:o});try{const i=await Cp(s,o,a);return le({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),le({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function dC({request:e,context:t}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await en()),!r)return le({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("scenarioId");if(!o)return le({error:"Missing required field: analysisId"},{status:400});const i=await Cp(o,a,r);return le({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const o=s instanceof Error?s.message:String(s),a=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",a),le({error:"Failed to setup debug environment",details:o},{status:500})}}const uC=Object.freeze(Object.defineProperty({__proto__:null,action:dC,loader:cC},Symbol.toStringTag,{value:"Module"}));function pC({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=Ce()||process.cwd(),o=G.resolve(s,r);if(!o.startsWith(s+G.sep)&&o!==s)return new Response("Path outside project root",{status:403});try{const a=q.readFileSync(o,"utf8");return new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const hC=Object.freeze(Object.defineProperty({__proto__:null,loader:pC},Symbol.toStringTag,{value:"Module"})),mC=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function kp(e){const t=jm("sha256",mC);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function fC(e,t){return t===kp(e)}async function gC({request:e}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return le({success:!1,error:"Unlock code is required"},{status:400});const s=await Ye();return s?fC(s,r)?(await or({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),le({success:!0})):le({success:!1,error:"Invalid unlock code"},{status:400}):le({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),le({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const yC=Object.freeze(Object.defineProperty({__proto__:null,action:gC},Symbol.toStringTag,{value:"Module"}));async function xC({request:e,context:t}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await en()),!r)return le({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("defaultWidth");if(!o||!a)return le({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(a,10);if(isNaN(i)||i<320||i>3840)return le({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const l=await AN(o,i,r);return console.log("[API] Recapture queued",l),le({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),le({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const bC=Object.freeze(Object.defineProperty({__proto__:null,action:xC},Symbol.toStringTag,{value:"Module"}));function vC(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(wC).map(o=>o===""?[]:o.split("/")).reduce((o,a)=>{const i=[];for(let l=0;l<Math.min(o.length,a.length)&&o[l]===a[l];l++)i.push(o[l]);return i}).join("/")}function wC(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(NC(s))r.pop();else break}return r.join("/")}function NC(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function SC({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=vC(r),o=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:o})}const CC=Object.freeze(Object.defineProperty({__proto__:null,loader:SC},Symbol.toStringTag,{value:"Module"}));function kC(e,t){var i,l,c,u,p;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||m?s?{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:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const o=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((u=e.metadata)!=null&&u.previousVersionWithAnalyses)||o){const h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((p=e.metadata)==null?void 0:p.previousVersionWithAnalyses);return s&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{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 s?{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 EC(e){return kC(e).hasOutdatedSimulations}function Ro(e,t,r,s,o){var J,j,D,A,L,E,F,I;const a=(J=t==null?void 0:t.scenarios)==null?void 0:J.find(K=>K.name===e.name),i=!!(a!=null&&a.startedAt),l=!!(a!=null&&a.screenshotStartedAt),c=!!(a!=null&&a.screenshotFinishedAt),u=!!(a!=null&&a.finishedAt),p=1800*1e3,h=l&&!c&&(a==null?void 0:a.screenshotStartedAt)&&Date.now()-new Date(a.screenshotStartedAt).getTime()>p,m=!!((D=(j=e.metadata)==null?void 0:j.screenshotPaths)!=null&&D[0])||!!((A=e.metadata)!=null&&A.executionResult),f=l&&!c,y=a==null?void 0:a.error,g=(E=(L=e.metadata)==null?void 0:L.executionResult)==null?void 0:E.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const K of t.errors)x.push({source:`${K.phase} phase`,message:K.message});if(t!=null&&t.steps)for(const K of t.steps)K.error&&x.push({source:K.name,message:K.error});const b=!m&&!y&&!g&&x.length>0,v=!!(y||g||h||b),N=h?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(b?`Analysis error: ${x[0].message}`:null),w=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(a==null?void 0:a.errorStack)||(g==null?void 0:g.stack)||null,S=(s&&o?o.jobs.some(K=>{var Q;return((Q=K.entityShas)==null?void 0:Q.includes(s))||K.type==="analysis"&&K.entityShas&&K.entityShas.length===0})||((I=(F=o.currentlyExecuting)==null?void 0:F.entityShas)==null?void 0:I.includes(s)):!1)&&!i&&!v||!!(a!=null&&a.analyzing)&&!i&&!v,k=i&&!l&&!u&&!v,T=(S||k||f)&&!v,_=(S||k)&&r===!1&&!m;let $;_?$="crashed":v?$="error":m||u?$="completed":f?$="capturing":k?$="starting":S?$="queued":$="pending";let M="📷",R="pending",z=!1,O=`Not captured: ${e.name}`;const U="border-gray-300",W=v||_?"bg-red-50":"bg-white";return v||_?(M="⚠️",R="error",O=`Error: ${_?"Analysis process crashed":N||"Unknown error"}`):S?(M="⋯",R="queued",O=`Queued: ${e.name}`):k?(M="⋯",R="starting",z=!0,O=`Starting server for ${e.name}...`):f&&!v?(M="⋯",R="capturing",z=!0,O=`Capturing ${e.name}...`):m&&(M="✓",R="completed",O=e.name),{hasError:v||_,errorMessage:_?"Analysis process crashed":N,errorStack:_?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:m,hasCrashed:_,isAnalyzing:T,isQueued:S,isServerStarting:k,status:$,icon:M,iconType:R,shouldSpin:z,title:O,borderColor:U,bgColor:W}}function Ep({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:o=!1}){var w,C,S,k,T,_;const a=Ro(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,l=!!i,u=(((S=(C=e.metadata)==null?void 0:C.data)==null?void 0:S.argumentsData)||[]).length,p=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((T=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:T.length)||0,m=((_=i==null?void 0:i.timing)==null?void 0:_.duration)||0;let f=0;u>0&&f++,u>2&&f++,p&&f++,h>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=a.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?o?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=s?`border-2 ${x.border}`:"",v=Array.from({length:3},($,M)=>n("div",{className:`w-1 h-1 rounded-full ${M<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},M)),N=a.hasError?`Error: ${a.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
493
|
+
${u} args → ${p?"value":"void"}${h>0?` (${h} logs)`:""}
|
|
494
|
+
${m}ms`:`Not executed: ${e.name}`;return d(ke,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${b} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,onClick:$=>$.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:a.hasError?"⚠":l?"ƒ":"○"}),l&&!a.hasError&&d("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:u}),n("span",{children:"→"}),n("span",{children:p?"✓":"∅"})]}),l&&!a.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),l&&!a.hasError&&m>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:m>1e3?`${Math.round(m/1e3)}s`:`${m}ms`}),l&&!a.hasError&&h>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Ha({size:e=24,className:t=""}){return d("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 Fc({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:o,size:a="medium",cacheBuster:i,className:l="",viewMode:c}){var g,x;if(t.entityType==="library")return n(Ep,{scenario:e,entitySha:t.sha,size:a==="small"?"small":"medium"});const p=Ro(e,r,o,t.sha,s),h=a==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:a==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},m=`relative ${h.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${b}/${c}`:b};if(p.isCaptured){const b=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(ke,{to:f(),className:`${m} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(ut,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const b={size:a==="small"?16:a==="large"?24:20,strokeWidth:2},v=n(Wi,{size:a});if(p.shouldSpin||p.iconType==="queued"||p.iconType==="pending")return v;switch(p.iconType){case"starting":case"capturing":return v;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Ha,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(lm,{...b});default:return v}};return n(ke,{to:f(),className:`${m} ${p.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:p.title,children:n("div",{className:h.iconSize,children:y()})})}const Xn=70;function _C({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:o,cacheBuster:a,activeTab:i,entityType:l,entity:c,queueState:u,processIsRunning:p,isEntityAnalyzing:h,areScenariosStale:m,viewMode:f,setViewMode:y,isBreakdownView:g,onCreateScenario:x}){var O,U,W,J,j,D;const b=ye(null),[v,N]=P(new Set),[w,C]=P(!1);se(()=>{b.current&&i==="scenarios"&&b.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const S=A=>`/entity/${o}/scenarios/${A}`,k=A=>{N(L=>{const E=new Set(L);return E.has(A)?E.delete(A):E.add(A),E})},T=(A,L=2)=>{const F=A.split(`
|
|
495
|
+
`).slice(0,L).join(" ").trim();return F.length>Xn?F.substring(0,Xn-3):(A.split(`
|
|
496
|
+
`).length>L||A.length>F.length,F)},_=pe(()=>{var L;if(!((L=r==null?void 0:r.metadata)!=null&&L.executionFlows)||!(r!=null&&r.scenarios))return null;const A=r.scenarios.filter(E=>{var F;return!((F=E.metadata)!=null&&F.sameAsDefault)});return Di(r.metadata.executionFlows,A)},[r]),$=(_==null?void 0:_.totalFlows)||0,M=(_==null?void 0:_.coveredFlows)||0,R=(_==null?void 0:_.coveragePercentage)||0;(O=c==null?void 0:c.metadata)!=null&&O.defaultWidth||(U=r==null?void 0:r.metadata)!=null&&U.defaultWidth;const z=(W=r==null?void 0:r.status)!=null&&W.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return d("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&d("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),d("div",{className:"grid grid-cols-2 gap-2",children:[d(ke,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(R),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(ke,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((j=e[0])==null?void 0:j.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[M,"/",$]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(ke,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((D=e[0])==null?void 0:D.id)}`:`/entity/${o}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),c&&c.filePath&&n("div",{children:n("button",{onClick:x,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] flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),z&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:z})]}),h&&(m||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("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((A,L)=>{const E=!g&&(s==null?void 0:s.id)===A.id,F=v.has(A.id||"");return A.id?d(ke,{to:S(A.id),ref:E?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${E?"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(Fc,{scenario:A,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:u,processIsRunning:p,size:"large",cacheBuster:a,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${F?"":"line-clamp-1"}`,children:A.name}),A.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[F?A.description:T(A.description),!F&&A.description.length>Xn&&d(ve,{children:["...",n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),k(A.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),F&&A.description.length>Xn&&n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),k(A.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})}),t.length>0&&!(h&&m)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("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&&d("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((A,L)=>{const E=!g&&(s==null?void 0:s.id)===A.id,F=v.has(A.id||"");return A.id?d(ke,{to:`/entity/${o}/scenarios/${A.id}`,ref:E?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${E?"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(Fc,{scenario:A,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:u,processIsRunning:p,size:"large",cacheBuster:a,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${F?"":"line-clamp-1"}`,children:A.name}),A.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[F?A.description:T(A.description),!F&&A.description.length>Xn&&d(ve,{children:["...",n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),k(A.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),F&&A.description.length>Xn&&n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),k(A.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})]})]})]})}function jC({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:o,onDelete:a,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:u=!1,onShowDeleteConfirm:p,isDeleting:h=!1,deleteError:m=null}){const[f,y]=P(""),g=async()=>{await r(f)},x=async b=>{await s(f,b),b||y("")};return d("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[d("div",{className:"border-b border-[#e1e1e1] pb-3",children:[d("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(ke,{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})]}),d("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[d("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:b=>y(b.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),d("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&d("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"}),d("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:o,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),c&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${c.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:c}),c==="Recapture successful"&&n("div",{children:n(ke,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),d("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"}),a&&d(ve,{children:[u?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void a(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>p==null?void 0:p(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>p==null?void 0:p(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),m&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:m})]})]})]})}function PC({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,o=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],a=u=>{var y,g,x;if(!u)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const p=[],h=((y=u.sideEffects)==null?void 0:y.consoleOutput)||[];h.length>0&&(p.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(b=>{p.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const m=((g=u.sideEffects)==null?void 0:g.fileWrites)||[];m.length>0&&(p.push(`
|
|
497
|
+
File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(b=>{p.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=u.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(p.push(`
|
|
498
|
+
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{p.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),u.error&&p.push(`
|
|
499
|
+
Error: ${u.error.name||"Error"}: ${u.error.message}`),p.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":p.join(`
|
|
500
|
+
`)};return d("div",{className:"flex w-full h-full gap-0",children:[d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(o,null,2)})})]}),d("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:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),d("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:a(s)})})]})]})}const An={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function As({scenarioId:e,analysisId:t}){const[r,s]=P(!1),[o,a]=P(!1),[i,l]=P(null),[c,u]=P(!1),p=e||t;if(!p)return null;const h=`/codeyam-diagnose ${p}`,m=async()=>{a(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{a(!1)}},f=()=>{s(!1),l(null)};return d(ve,{children:[d("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:An.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:An.subtext},children:"Simply run this command in Claude Code:"}),d("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:An.commandBoxBg,borderColor:An.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:An.commandBoxText},children:h}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(h),u(!0),setTimeout(()=>u(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:c?"#22c55e":An.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(Mt,{size:14}):n(Ot,{size:14})})]}),d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void m(),disabled:o,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:An.link},children:o?"capturing...":"please do so here"}),"."]})]}),n(Rd,{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 Rc=1440,Ts=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Vt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function _p({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:o,hasScenarios:a,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:u,queueState:p}){var H,ne,oe,Z,re,ue,we,je,be,Ee,X;const h=Ke(),[m,f]=P(!1),[y,g]=P(!1),[x,b]=P({name:"Desktop",width:Rc,height:900}),[v,N]=P(Rc),[w,C]=P(1),{customSizes:S,addCustomSize:k,removeCustomSize:T}=No(l),_=pe(()=>[...Ts,...S],[S]),$=(fe,ae)=>{N(fe);const ie=_.find(he=>he.width===fe&&he.height===ae);b({name:(ie==null?void 0:ie.name)||"Custom",width:fe,height:ae})},M=fe=>{N(fe.width),b({name:fe.name,width:fe.width,height:fe.height})},R=fe=>{k(fe,x.width,x.height??900),g(!1),b(ae=>({...ae,name:fe}))},z=(fe,ae)=>{N(fe);const ie=_.find(he=>he.width===fe&&he.height===ae);b(he=>({name:(ie==null?void 0:ie.name)||"Custom",width:fe,height:he.height}))},O=(ne=(H=e==null?void 0:e.metadata)==null?void 0:H.screenshotPaths)==null?void 0:ne[0],U=pe(()=>e?Ro(e,t==null?void 0:t.status,u,r==null?void 0:r.sha,p):null,[e,t==null?void 0:t.status,u,r==null?void 0:r.sha,p]),W=pe(()=>{var ae,ie;const fe=[];if((ae=t==null?void 0:t.status)!=null&&ae.errors&&t.status.errors.length>0)for(const he of t.status.errors)fe.push({source:`${he.phase} phase`,message:he.message,stack:he.stack});if((ie=t==null?void 0:t.status)!=null&&ie.steps)for(const he of t.status.steps)he.error&&fe.push({source:he.name,message:he.error,stack:he.errorStack});return fe},[(oe=t==null?void 0:t.status)==null?void 0:oe.errors,(Z=t==null?void 0:t.status)==null?void 0:Z.steps]),J=(U==null?void 0:U.errorMessage)||null,j=(U==null?void 0:U.errorStack)||null,{interactiveServerUrl:D,isStarting:A,isLoading:L,showIframe:E,iframeKey:F,onIframeLoad:I}=Bn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),K=pe(()=>D||null,[D]),Q=!i&&a&&e&&!((ue=(re=e.metadata)==null?void 0:re.screenshotPaths)!=null&&ue[0])&&((je=(we=t==null?void 0:t.status)==null?void 0:we.scenarios)==null?void 0:je.some(fe=>fe.name===e.name&&fe.screenshotStartedAt&&!fe.screenshotFinishedAt)),{lastLine:V}=Qt(l,i||s==="interactive"||Q||!1);if(!e){if(i&&r)return d(ve,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:d("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:Q?"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."}),V&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:V}),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"})]})}),m&&l&&n(hn,{projectSlug:l,onClose:()=>f(!1)})]});if(!a&&r&&!i){if(W.length>0){const fe=W.length===1?((be=W[0])==null?void 0:be.message)||"An error occurred during analysis.":`${W.length} errors occurred during analysis.`;return d(ve,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:Vt.background,border:`2px solid ${Vt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(Ha,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:Vt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",fe," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:Vt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(As,{analysisId:t==null?void 0:t.id})})]})}),m&&l&&n(hn,{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:d("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return d(ve,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
501
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
502
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
503
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
504
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
505
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||Q&&!O)&&!J&&s==="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:d("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[d("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:Q?`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:Q?`Taking screenshots for ${((Ee=t==null?void 0:t.scenarios)==null?void 0:Ee.length)||0} scenario${((X=t==null?void 0:t.scenarios)==null?void 0:X.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&d("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),V&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:d("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),d("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:V,children:V})]})]})}),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."})]})}):s==="screenshot"&&(O||J)||s==="interactive"&&(K||A)||s==="data"?d(ve,{children:[J&&!O&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:Vt.background,border:`2px solid ${Vt.border}`,maxHeight:"50vh"},role:"alert",children:d("div",{className:"flex flex-col gap-3",children:[d("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:Vt.text},children:[n(Ha,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),d("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:Vt.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:Vt.text},children:J})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(As,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?d("div",{className:"flex-1 flex flex-col min-h-0",children:[K&&d("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(Fx,{presets:[...Ts],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:$,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:T}),e&&r&&d(ke,{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"]})]}),K&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${Ts[Ts.length-1].width}px`,width:"100%"},children:n(gi,{currentViewportWidth:v,currentPresetName:x.name,onDevicePresetClick:M,devicePresets:_})})}),n(Mo,{scenarioId:e.id,scenarioName:e.name,iframeUrl:K,isStarting:A,isLoading:L,showIframe:E,iframeKey:F,onIframeLoad:I,onScaleChange:C,onDimensionChange:z,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(PC,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${v}px`},children:(O||!J)&&n(ut,{screenshotPath:O,cacheBuster:o,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!O?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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),d("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),d("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."]}),V&&d("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:V})]}),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?d("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!c&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:d("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[d("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"})]}),d("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."}),d("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(ke,{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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("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."}),d("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})})]}),j&&d("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:j})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(As,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):W.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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:W,title:"Analysis Error",description:W.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${W.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(As,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),m&&l&&n(hn,{projectSlug:l,onClose:()=>f(!1)}),y&&n(yi,{width:x.width,height:x.height??900,onSave:R,onCancel:()=>g(!1)})]})}function AC({analysis:e,entitySha:t,onCreateScenario:r}){Bt();const[s,o]=P(e);se(()=>{o(e)},[e]);const[a,i]=P(null),l=pe(()=>{var m;if(!((m=s==null?void 0:s.metadata)!=null&&m.executionFlows)||!(s!=null&&s.scenarios))return null;const h=s.scenarios.filter(f=>{var y;return!((y=f.metadata)!=null&&y.sameAsDefault)});return Di(s.metadata.executionFlows,h)},[s]),c=pe(()=>l?kb(l):[],[l]),u=pe(()=>s!=null&&s.scenarios?s.scenarios.filter(h=>{var m;return!((m=h.metadata)!=null&&m.sameAsDefault)}):[],[s]),p=h=>{var f;const m=((f=h.metadata)==null?void 0:f.coveredFlows)||[];return l?l.executionFlows.filter(y=>m.includes(y.id)):[]};return s?!l||l.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("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:d("div",{className:"p-6 space-y-6",children:[d("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"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:u.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:l.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[l.coveredFlows,"/",l.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${l.coveragePercentage===100?"text-green-600":l.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[l.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),d("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:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",u.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:u.length===0?d("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n("button",{onClick:r,className:"text-blue-600 hover:underline bg-transparent border-none cursor-pointer p-0 text-sm",children:"Create one"})]}):u.map(h=>{var y,g,x;const m=(g=(y=h.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0],f=p(h);return d("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(ut,{screenshotPath:m,alt:h.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(ke,{to:`/entity/${t}/scenarios/${h.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:h.name}),((x=h.metadata)==null?void 0:x.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:h.description}),f.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:f.map(b=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${b.isError?"bg-red-50 text-red-700":b.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:b.name},b.id))})]})]},h.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:d("button",{onClick:r,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 border-none cursor-pointer",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(h=>d("span",{className:`text-xs px-2 py-0.5 rounded ${h.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[h.name,h.impact==="high"&&" (high impact)"]},h.id)),c.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),d("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:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",l.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:l.executionFlows.map(h=>{const m=a===h.id,f=h.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>i(m?null:h.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:d("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?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:h.name}),f?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"}),h.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),h.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),h.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),h.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:h.description})]})]})}),m&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[h.requiredValues.length>0&&d("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:h.requiredValues.map((y,g)=>d("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:y.attributePath}),n("span",{className:"text-gray-400",children:y.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:y.value})]},g))})]}),f&&d("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:h.usedInScenarios.map(y=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:y.name},y.id))})]}),h.codeSnippet&&d("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:h.codeSnippet})})]})]})]},h.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("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 Dc({hasIndirectBadge:e,onAnalyze:t}){return d(ve,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("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"})]})}),d("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 TC({entity:e,history:t}){const[r,s]=P("entity"),[o,a]=P(new Set),i=t.filter(p=>p.analyses.length>0).length,l=pe(()=>{const p=new Map;return t.forEach(h=>{h.analyses.forEach(m=>{(m.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{p.has(y.name)||p.set(y.name,[]),p.get(y.name).push({version:h,analysis:m,scenario:y})})})}),Array.from(p.entries()).map(([h,m])=>{var f;return{name:h,description:((f=m[0])==null?void 0:f.scenario.description)||"",versions:m.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,u=p=>{a(h=>{const m=new Set(h);return m.has(p)?m.delete(p):m.add(p),m})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("button",{onClick:()=>s("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})]}),d("button",{onClick:()=>s("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:c})]})]})}),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"?d("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((p,h)=>d("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]"}),d("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:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[p.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"}),d(ke,{to:`/entity/${p.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:p.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:p.createdAt&&new Date(p.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),p.analyses.length>0?n("div",{children:p.analyses.map((m,f)=>{var g;const y=(m.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:y.length===0?n(Dc,{hasIndirectBadge:m.indirect,onAnalyze:()=>{console.log("Analyze version:",p.sha)}}):d(ve,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[m.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=m.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[d("span",{className:"font-medium",children:["What Changed:"," "]}),m.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,b)=>{var w,C;const v=(C=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],N=`${x.name}-${b}`;return d(ke,{to:`/entity/${p.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:v?n(ut,{screenshotPath:v,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("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})})]},N)})})})]})},m.id||f)})}):n(Dc,{onAnalyze:()=>{console.log("Analyze version:",p.sha)}})]})]},p.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((p,h)=>{const m=o.has(p.name),f=m?p.versions:p.versions.slice(0,1),y=p.versions.length-1,g=p.versions[0];return g==null||g.version.sha,e==null||e.sha,d("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]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("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:p.name}),p.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:p.description})]}),d("div",{className:"p-5 bg-white",children:[f.map((x,b)=>{var k,T;const{version:v,analysis:N,scenario:w}=x,C=(T=(k=w.metadata)==null?void 0:k.screenshotPaths)==null?void 0:T[0],S=b===0;return d("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(ke,{to:`/entity/${v.sha}/scenarios/${w.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:C?n(ut,{screenshotPath:C,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("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"})]})}),d("div",{className:"flex-1 flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[v.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),S&&p.versions.length>1&&d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[p.versions.length," versions"]})]}),d(ke,{to:`/entity/${v.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:v.sha.substring(0,8)})]}),N.createdAt&&d("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${b}`)}),y>0&&d("button",{onClick:()=>u(p.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${m?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),m?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},p.name)})})]})})}function Ic({entity:e,analysisInfo:t,from:r}){const s=Ke(),o=s.state!=="idle",a=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),a&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(ke,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:d("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(ut,{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(St,{type:e.entityType})})}),d("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(St,{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&&d("div",{className:"flex items-center gap-2 mt-2",children:[d("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"?d(ve,{children:[d("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"})]}),a&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?d("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"})]}):d(ve,{children:[d("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"})]}),a&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Oc=e=>{var o,a,i;const t=((o=e.analysisStatus)==null?void 0:o.status)||"not_analyzed",r=((a=e.analysisStatus)==null?void 0:a.scenarioCount)||0,s=(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:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function MC({importedEntities:e,importingEntities:t}){const[r]=lr(),s=r.get("from"),o=Ke(),a=o.state!=="idle",i=e.length>0,l=t.length>0,c=m=>m.filter(f=>f.entityType==="visual"||f.entityType==="library"),u=m=>{const f=c(m);f.length!==0&&o.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},p=c(e).length>0,h=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("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."})]}),p&&n("button",{onClick:()=>u(e),disabled:a,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:a?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(m=>n(Ic,{entity:m,analysisInfo:Oc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>u(t),disabled:a,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:a?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(m=>n(Ic,{entity:m,analysisInfo:Oc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function $C({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(MC,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function FC({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Hr,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Hr({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:o,showInlineToggle:a=!1}){const[i,l]=P(r||t<2);if(se(()=>{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 c=typeof e;if(c==="string")return d("span",{className:"text-green-600",children:['"',e,'"']});if(c==="number")return n("span",{className:"text-blue-600",children:e});if(c==="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:"[]"}):d("span",{children:[d("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:[d("span",{children:[i?"▼":"▶"," ","["]}),!i&&d("span",{children:[e.length,"]"]})]}),i?d(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((u,p)=>n("div",{className:"py-0.5",children:n(Hr,{data:u,depth:t+1,defaultExpanded:r,maxDepth:s})},p))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const u=Object.keys(e);if(u.length===0)return n("span",{className:"text-gray-600",children:"{}"});const p=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=m=>Array.isArray(m)&&m.length>0;return d("span",{children:[d("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:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[u.length,"}"]})]}),i?d(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:u.map(m=>{const f=e[m],y=p(f),g=h(f);return n("div",{className:"py-0.5",children:y?n(Ji,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(Hi,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(ve,{children:[d("span",{className:"text-orange-600",children:[m,": "]}),n(Hr,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},m)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Ji({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:o}){const[a,i]=P(s||r<2),l=Object.keys(t);return se(()=>{i(s||r<2)},[s,r]),d(ve,{children:[d("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(!a),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:a?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!a&&d("span",{className:"text-gray-600",children:[l.length,"}"]})]}),a&&d(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const u=t[c],p=u!==null&&typeof u=="object"&&!Array.isArray(u)&&Object.keys(u).length>0,h=Array.isArray(u)&&u.length>0;return n("div",{className:"py-0.5",children:p?n(Ji,{propertyKey:c,value:u,depth:r+1,defaultExpanded:s,maxDepth:o}):h?n(Hi,{propertyKey:c,value:u,depth:r+1,defaultExpanded:s,maxDepth:o}):d(ve,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(Hr,{data:u,depth:r+2,defaultExpanded:s,maxDepth:o})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Hi({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:o}){const[a,i]=P(s||r<2);return se(()=>{i(s||r<2)},[s,r]),d(ve,{children:[d("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(!a),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:a?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!a&&d("span",{className:"text-gray-600",children:[t.length,"]"]})]}),a&&d(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const u=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,p=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:u?n(Ji,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:o}):p?n(Hi,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:o}):n(Hr,{data:l,depth:r+2,defaultExpanded:s,maxDepth:o})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function va({label:e,count:t,isActive:r,onClick:s,badgeColorActive:o,badgeTextActive:a}){return d("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${o} ${a}`:"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 Lc({label:e,isActive:t,onClick:r,disabled:s=!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:s,children:e})}function zc({call:e,scenarioName:t}){const[r,s]=P(!1),[o,a]=P("system"),i=m=>new Date(m).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=m=>m?`$${m.toFixed(4)}`:null,c=(m,f)=>{if(!m&&!f)return null;const y=[];return m&&y.push(`${m.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},u=pe(()=>{var m,f,y,g,x;try{const b=JSON.parse(e.response);return(y=(f=(m=b.choices)==null?void 0:m[0])==null?void 0:f.message)!=null&&y.content?b.choices[0].message.content:(x=(g=b.content)==null?void 0:g[0])!=null&&x.text?b.content[0].text:e.response}catch{return e.response}},[e.response]),p=pe(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=pe(()=>{var m;if(t)return t;try{const f=JSON.parse(e.props);return((m=f==null?void 0:f.scenario)==null?void 0:m.name)||null}catch{return null}},[e.props,t]);return d("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:()=>s(!r),children:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("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&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>a("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>a("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>a("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>a("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),o&&d("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),o==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),o==="response"&&d("div",{children:[e.error&&d("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:u})]}),o==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:p})]}),e.error&&!o&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Bc=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function RC({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:o}){var N,w,C,S,k,T,_,$,M;const[a,i]=P("entity"),[l,c]=P("analysis"),[u,p]=P(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,m]=P("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=pe(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const R=[...o.entityCalls,...o.analysisCalls],z=R.filter(U=>U.object_type==="entity"||Bc.includes(U.prompt_type)),O=R.filter(U=>U.object_type!=="entity"&&!Bc.includes(U.prompt_type));return z.sort((U,W)=>W.created_at-U.created_at),O.sort((U,W)=>W.created_at-U.created_at),{entityLlmCalls:z,scenarioLlmCalls:O,totalLlmCalls:R.length}},[o]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(w=t==null?void 0:t.metadata)==null?void 0:w.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(S=(C=e==null?void 0:e.metadata)==null?void 0:C.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":(T=e==null?void 0:e.metadata)==null?void 0:T.importedExports,"External Dependencies":(_=e==null?void 0:e.metadata)==null?void 0:_.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:($=t==null?void 0:t.metadata)==null?void 0:$.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter(R=>R.data!==void 0&&R.data!==null).length;let v=null;if(a==="entity"){const R=x.find(z=>z.id===l);R&&R.data!==void 0&&R.data!==null&&(v={title:R.title,description:R.description,data:R.data})}else if(a==="scenarios"&&u){const R=r.find(z=>(z.id||z.name)===u.scenarioId);R&&(v={title:R.name,description:R.description||"Scenario data and configuration",data:R.metadata})}return d("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:d("div",{className:"flex border-b border-gray-200 relative",children:[n(va,{label:"Entity",isActive:a==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(va,{label:"Scenarios",count:r.length,isActive:a==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(va,{label:"LLM Calls",count:g,isActive:a==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((M=t==null?void 0:t.metadata)==null?void 0:M.analyzerVersion)&&d("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})]})]})}),a==="llm-calls"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>m("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),d("button",{onClick:()=>m("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(R=>n(zc,{call:R},R.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(R=>n(zc,{call:R},R.id))})]}):d("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:a==="entity"?d(ve,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(R=>{const z=R.data!==void 0&&R.data!==null;return n(Lc,{label:R.title,isActive:l===R.id,onClick:()=>c(R.id),disabled:!z},R.id)})})]}):d(ve,{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(R=>{const z=R.id||R.name,O=(u==null?void 0:u.scenarioId)===z;return n(Lc,{label:R.name,isActive:O,onClick:()=>p({scenarioId:z})},z)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(DC,{title:v.title,description:v.description,data:v.data}):a==="scenarios"&&r.length===0?n(Yc,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):a==="entity"?n(Yc,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Yc({title:e,description:t,onAnalyze:r}){return d("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 DC({title:e,description:t,data:r}){const[s,o]=P(!0);return d(ve,{children:[d("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})]}),d("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>o(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>o(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(xt,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),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(FC,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function IC({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const o=Ke();return se(()=>{if(e!=null&&e.sha&&o.state==="idle"&&!o.data){const a=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;o.load(a)}},[e==null?void 0:e.sha,t==null?void 0:t.id,o.state,o.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(RC,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:o.data})})}const OC={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},LC={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},zC=2e3,BC=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 YC({entity:e,entityCode:t}){const r=Vr(),s=ye(null);return se(()=>{const o=r.hash;if(!o||!s.current)return;const a=o.match(/^#L(\d+)$/);if(!a)return;const i=parseInt(a[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const c=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=c},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:d("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[d("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(xt,{content:t,label:"Copy Code",duration:zC,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(Om,{language:BC(e==null?void 0:e.filePath),style:Lm,showLineNumbers:!0,customStyle:OC,lineNumberStyle:LC,wrapLines:!0,lineProps:o=>({"data-line-number":o,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}function qt({prompt:e,height:t=300,onClose:r,hideHeader:s}){const o=ye(null),a=ye(null),i=ye(null),l=ye(!1),c=ye(e);se(()=>{const p=o.current;if(!p)return;let h=!1,m=null;async function f(){const[y,g]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit")]);if(h)return;{let _=document.getElementById("xterm-css");_||(_=document.createElement("style"),_.id="xterm-css",document.head.appendChild(_)),_.textContent=`
|
|
506
|
+
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
507
|
+
.xterm.focus, .xterm:focus { outline: none; }
|
|
508
|
+
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
509
|
+
.xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
|
|
510
|
+
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
511
|
+
.xterm .composition-view.active { display: block; }
|
|
512
|
+
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
513
|
+
.xterm .xterm-screen { position: relative; }
|
|
514
|
+
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
515
|
+
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
516
|
+
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
517
|
+
.xterm.enable-mouse-events { cursor: default; }
|
|
518
|
+
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
519
|
+
.xterm.column-select.focus { cursor: crosshair; }
|
|
520
|
+
.xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
521
|
+
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
522
|
+
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
523
|
+
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
524
|
+
.xterm-dim { opacity: 1 !important; }
|
|
525
|
+
.xterm-underline-1 { text-decoration: underline; }
|
|
526
|
+
.xterm-underline-2 { text-decoration: double underline; }
|
|
527
|
+
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
528
|
+
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
529
|
+
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
530
|
+
.xterm-overline { text-decoration: overline; }
|
|
531
|
+
.xterm-strikethrough { text-decoration: line-through; }
|
|
532
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
533
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
534
|
+
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
535
|
+
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
536
|
+
`}const x=new y.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),b=new g.FitAddon;x.loadAddon(b),x.open(p),requestAnimationFrame(()=>{try{b.fit()}catch{}}),i.current=x;let v=null;try{const _=await fetch("/api/editor-scenario-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c.current})});_.ok&&(v=(await _.json()).promptFile)}catch{}if(h)return;const N=window.location.protocol==="https:"?"wss:":"ws:",w=window.location.host,C=new URLSearchParams;C.set("entityName","inline-claude");const S=`${N}//${w}/ws/terminal?${C.toString()}`,k=new WebSocket(S);a.current=k,k.onopen=()=>{k.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))};let T=!1;k.onmessage=_=>{try{const $=JSON.parse(_.data);if($.type==="session-id"&&!T){T=!0,setTimeout(()=>{const M=v?`claude "Read the file at '${v.replace(/'/g,"'\\''")}' for your instructions."`:"claude";k.send(JSON.stringify({type:"input",data:M+"\r"}))},300);return}if($.type==="output"&&$.data){x.write($.data);return}}catch{x.write(_.data)}},k.onclose=()=>{l.current||x.write(`\r
|
|
537
|
+
\x1B[90m--- Session ended ---\x1B[0m\r
|
|
538
|
+
`)},k.onerror=()=>{x.write(`\r
|
|
539
|
+
\x1B[31mConnection error\x1B[0m\r
|
|
540
|
+
`)},x.onData(_=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"input",data:_}))}),m=new ResizeObserver(()=>{try{b.fit(),k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))}catch{}}),m.observe(p)}return f(),()=>{var y,g;h=!0,l.current=!0,m==null||m.disconnect(),((y=a.current)==null?void 0:y.readyState)===WebSocket.OPEN&&a.current.close(),(g=i.current)==null||g.dispose()}},[]);const u=t==="100%";return d("div",{className:s?"":"border-t border-[#2d2d2d]",style:u?{height:"100%",display:"flex",flexDirection:"column"}:void 0,children:[!s&&d("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[#1e1e1e]",children:[n("span",{className:"text-[10px] font-medium text-[#00a0c4]",children:"Claude"}),r&&n("button",{onClick:r,className:"text-gray-500 hover:text-gray-300 text-[10px] bg-transparent border-none cursor-pointer",children:"Close"})]}),n("div",{ref:o,style:{height:u?void 0:t,flex:u?1:void 0,background:"#1a1a1a",padding:"4px 0",position:"relative",overflow:"hidden"}})]})}const UC=Object.freeze(Object.defineProperty({__proto__:null,MiniClaudeChat:qt},Symbol.toStringTag,{value:"Module"})),WC=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function JC({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:o,defaultShouldRevalidate:a}){return r.pathname===s.pathname&&r.search===s.search?a:!!(e.sha!==t.sha||o)}async function HC({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const a=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),c=l[0]||"scenarios",u=l[1]||null,p=l[2]||null,h=r.analysisQueue,m=h?h.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([In(s),Ye(),hr(),Qg(Ce()||process.cwd())]),b=f?await fo(f):null,v=f?await qd(f.sha):null;let N={importedEntities:[],importingEntities:[]},w=null,C=[];f&&(N=await Qd(f),w=await Zd(f),C=await eu(f));const S=!!(f&&C.length>0&&C[0].sha!==f.sha),k=C.length>0?C[0].sha:null,T=!!(C.length>0&&C[0].analyses&&C[0].analyses.length>0),_=f?await Xd(f):!1;return le({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:v??void 0,projectSlug:y,from:a,relatedEntities:N,entityCode:w??void 0,hasNewerVersion:S,newestEntitySha:k,newestVersionHasAnalysis:T,fileModifiedSinceEntity:_,history:C,tab:c,scenarioId:u,viewModeFromUrl:p,currentCommit:g,hasAnApiKey:x,queueState:m})}const VC=nt(function(){var sn,on,Ht,vn,Er,_r,os,as,is,ls,cs,Wn,ds,us,ps;const t=lt(),o=(kd()["*"]||"").split("/").filter(Boolean),a=o[0]||"scenarios",i=o[1]||null,l=o[2]||null,c=t.entity,u=t.analysis,p=t.currentEntityAnalysis,h=p||u,m=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,v=t.fileModifiedSinceEntity,N=t.history,w=t.currentCommit,C=t.hasAnApiKey,S=t.queueState;(sn=h==null?void 0:h.status)==null||sn.errors;const k=(h==null?void 0:h.scenarios)||[],T=k.filter(ge=>{var Fe;return!((Fe=ge.metadata)!=null&&Fe.sameAsDefault)}),_=k.filter(ge=>{var Fe;return(Fe=ge.metadata)==null?void 0:Fe.sameAsDefault}),$=zt(),M=ye(null);se(()=>{M.current===null&&(M.current=window.history.length)},[]);const R=()=>{if(typeof window>"u")return;const ge=window.history.state;if(ge===null||(ge==null?void 0:ge.idx)===void 0||(ge==null?void 0:ge.idx)===0)$("/");else{const Fe=window.history.length,rt=M.current;if(rt!==null&&Fe>rt){const ze=Fe-rt+1;$(-ze)}else $(-1)}},z=!!S.currentlyExecuting,O=a,U=(on=w==null?void 0:w.metadata)==null?void 0:on.currentRun,W=!!(U!=null&&U.createdAt)&&!(U!=null&&U.analysisCompletedAt),J=!!(c!=null&&c.sha&&((Ht=U==null?void 0:U.currentEntityShas)!=null&&Ht.includes(c.sha))),j=!!(c!=null&&c.sha&&((Er=(vn=S.currentlyExecuting)==null?void 0:vn.entityShas)!=null&&Er.includes(c.sha))),D=!!(c!=null&&c.sha&&((_r=S.jobs)!=null&&_r.some(ge=>{var Fe;return(Fe=ge.entityShas)==null?void 0:Fe.includes(c.sha)}))),A=J||j||D,L=A&&((os=h==null?void 0:h.status)==null?void 0:os.finishedAt)!=null&&T.length>0&&h.entitySha!==(c==null?void 0:c.sha),E=pe(()=>{if(O!=="scenarios")return null;if(i){const ge=T.find(Fe=>Fe.id===i);if(ge)return ge}return T.length>0&&!A?T[0]:null},[O,i,T,A]),F=((ls=(is=(as=E==null?void 0:E.metadata)==null?void 0:as.executionResult)==null?void 0:is.error)==null?void 0:ls.message)||((ds=(Wn=(cs=h==null?void 0:h.status)==null?void 0:cs.errors)==null?void 0:Wn[0])==null?void 0:ds.message);Yt({source:E?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:E==null?void 0:E.id,analysisId:h==null?void 0:h.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:E==null?void 0:E.name,errorMessage:F});const[I,K]=P(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");se(()=>{l&&l!==I&&l!=="edit"&&K(l)},[l]);const Q=l==="edit",[V,Y]=P(!1),[B,H]=P(!1),[ne,oe]=P(null),[Z,re]=P(!1),[ue,we]=P(!1),[je,be]=P(null),[Ee,X]=P(null),[fe,ae]=P(0),{interactiveServerUrl:ie,isStarting:he,isLoading:Te,showIframe:xe,iframeKey:Oe,onIframeLoad:Je}=Bn({analysisId:h==null?void 0:h.id,scenarioId:E==null?void 0:E.id,scenarioName:E==null?void 0:E.name,projectSlug:m,enabled:Q&&!!E,refreshTrigger:fe}),[bt,Ge]=P(!1),[xr,pt]=P(""),[qe,Wt]=P(!1),[br,nn]=P(Date.now()),[vr,Yn]=P(!1),[Un,Ft]=P(!1),ht=Ke(),mt=Ke(),ft=Ke(),ct=Bt(),wr=S.jobs.some(ge=>{var Fe;return(c==null?void 0:c.sha)&&((Fe=ge.entityShas)==null?void 0:Fe.includes(c.sha))||ge.type==="analysis"&&ge.commitSha===(w==null?void 0:w.sha)&&ge.entityShas&&ge.entityShas.length===0}),Le=A,Jt=((us=c==null?void 0:c.metadata)==null?void 0:us.defaultWidth)||((ps=h==null?void 0:h.metadata)==null?void 0:ps.defaultWidth)||1440,ts=Math.round(Jt*(900/1440));ht.state==="submitting"||ht.state,pe(()=>{var ge;return!!((ge=E==null?void 0:E.metadata)!=null&&ge.interactiveExamplePath)},[E]);const{isCompleted:Nr}=Qt(m,qe);se(()=>{ht.state==="idle"&&ht.data&&(ht.data.success?setTimeout(()=>{nn(Date.now()),ct.revalidate(),Wt(!1)},1500):ht.data.error&&(Wt(!1),alert(`Recapture failed: ${ht.data.error}`)))},[ht.state,ht.data,ct]),se(()=>{qe&&Nr&&setTimeout(()=>{nn(Date.now()),ct.revalidate(),Wt(!1)},1500)},[qe,Nr,ct]),se(()=>{mt.state==="idle"&&mt.data&&(mt.data.success?setTimeout(()=>{nn(Date.now()),ct.revalidate(),Wt(!1)},1500):mt.data.error&&(Wt(!1),alert(`Recapture failed: ${mt.data.error}`)))},[mt.state,mt.data,ct]);const dt=pe(()=>{var rt;if(!c)return"";const ge=[];if(ge.push(`# Create a New Scenario for "${c.name}"`),ge.push(""),ge.push(`**Entity**: ${c.name}`),ge.push(`**Type**: ${c.entityType}`),c.filePath&&ge.push(`**File**: ${c.filePath}`),ge.push(""),T.length>0){ge.push("## Existing Scenarios");for(const ze of T)ge.push(`- **${ze.name}**${ze.description?`: ${ze.description}`:""}`);ge.push("")}const Fe=(rt=h==null?void 0:h.metadata)==null?void 0:rt.executionFlows;if(Fe&&Fe.length>0){ge.push("## Execution Flows");const ze=new Set(T.flatMap(He=>{var at;return((at=He.metadata)==null?void 0:at.coveredFlows)||[]})),ot=Fe.filter(He=>!ze.has(He.id)),yt=Fe.filter(He=>ze.has(He.id));if(yt.length>0){ge.push(`### Covered (${yt.length})`);for(const He of yt)ge.push(`- ${He.name}${He.description?`: ${He.description}`:""}`);ge.push("")}if(ot.length>0){ge.push(`### Uncovered (${ot.length}) — gaps to consider`);for(const He of ot)ge.push(`- ${He.name}${He.description?`: ${He.description}`:""}${He.impact==="high"?" **(high impact)**":""}`);ge.push("")}}return ge.push("## Your Task"),ge.push("Ask the user what scenario they would like to create. Offer two options:"),ge.push("1. **Describe a scenario** — the user tells you what they want and you create it"),ge.push("2. **Analyze gaps** — you review the existing scenarios and execution flows to suggest scenarios that would improve coverage"),ge.push(""),ge.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),ge.join(`
|
|
541
|
+
`)},[c,T,h]),Sr=()=>{Ft(!0)},ns=()=>{c&&(g&&x&&x!==c.sha?($(`/entity/${x}/scenarios`),setTimeout(()=>{ft.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):ft.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};se(()=>{ft.state==="idle"&&ft.data&&(ft.data.success?ct.revalidate():ft.data.error&&alert(`Analysis failed: ${ft.data.error}`))},[ft.state,ft.data,c==null?void 0:c.sha,ct]),se(()=>{const ge=setTimeout(()=>{ct.revalidate()},500);return()=>clearTimeout(ge)},[]),se(()=>{if(W||Le){const ge=setInterval(()=>{ct.revalidate()},3e3);return()=>clearInterval(ge)}},[W,Le,ct]);const rs=(ge,Fe)=>ge==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${ge}`,ss=(ge,Fe)=>`/entity/${c==null?void 0:c.sha}/scenarios/${ge}/${Fe}`,Xe=ge=>{K(ge),E!=null&&E.id&&(ge==="interactive"?$(`/entity/${c==null?void 0:c.sha}/scenarios/${E.id}/fullscreen`,{replace:!0}):$(ss(E.id,ge),{replace:!0}))},gt=async ge=>{var Fe,rt;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ge,hasSelectedScenario:!!E,hasAnalysis:!!h}),!E||!h){const ze="Error: No scenario or analysis available";console.error("[EntityDetail]",ze),oe(ze);return}Y(!0),oe(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ge,scenarioId:E.id,scenarioName:E.name,currentData:E.data});try{const ze=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ge,existingScenarios:h.scenarios,scenariosDataStructure:(Fe=h.metadata)==null?void 0:Fe.scenariosDataStructure,editingMockName:E.name,editingMockData:Ee||((rt=E.metadata)==null?void 0:rt.data)})}),ot=await ze.json();if(!ze.ok||!ot.success)throw new Error(ot.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",ot.data),X(ot.data);const yt=(h.scenarios||[]).map(Ve=>Ve.id===E.id?{...Ve,metadata:{...Ve.metadata,data:ot.data}}:Ve),He=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:yt})}),at=await He.json();if(!He.ok||!at.success)throw console.error("[EntityDetail] Temp save failed:",at),new Error(at.error||"Failed to apply preview");if(oe("Generating preview. Capturing screenshot..."),ie){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ie});const Ve=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ie,scenarioId:E.id,projectId:h.projectId,viewportWidth:1440})}),wn=await Ve.json();!Ve.ok||!wn.success?(console.error("[EntityDetail] Direct capture failed:",wn),oe("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),oe('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ve=new FormData;Ve.append("analysisId",h.id||""),Ve.append("scenarioId",E.id||"");const wn=await fetch("/api/recapture-scenario",{method:"POST",body:Ve}),Nn=await wn.json();!wn.ok||!Nn.success?(console.warn("[EntityDetail] Recapture failed:",Nn.error),oe("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Nn.jobId),oe('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ae(Ve=>Ve+1),ct.revalidate()}catch(ze){console.error("Error applying changes:",ze),oe(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{Y(!1)}},Cr=async(ge,Fe)=>{var rt;if(!E||!h){oe("Error: No scenario or analysis available");return}H(!0),oe(null),console.log("[EntityDetail] Saving scenario to database",{description:ge,saveAsNew:Fe});try{const ze=Ee||((rt=E.metadata)==null?void 0:rt.data);let ot;if(Fe){const at={...E,id:`${E.name}-${Date.now()}`,name:`${E.name} (Copy)`,metadata:{...E.metadata,data:ze},description:ge||E.description};ot=[...h.scenarios||[],at]}else ot=(h.scenarios||[]).map(at=>at.id===E.id?{...at,metadata:{...at.metadata,data:ze},description:ge||at.description}:at);const yt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:ot})}),He=await yt.json();if(!yt.ok||!He.success)throw new Error(He.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),oe(Fe?"New scenario created successfully":"Scenario saved successfully"),X(null),ct.revalidate()}catch(ze){console.error("Error saving scenario:",ze),oe(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{H(!1)}},Oo=()=>{E!=null&&E.id&&(c!=null&&c.sha)&&$(`/entity/${c.sha}/scenarios/${E.id}/dev`)},Lo=async()=>{var ge;if(!(E!=null&&E.id)){be("Cannot delete scenario without ID");return}re(!0),be(null);try{const Fe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:E.id,screenshotPaths:((ge=E.metadata)==null?void 0:ge.screenshotPaths)||[]})}),rt=await Fe.json();if(!Fe.ok||!rt.success)throw new Error(rt.error||"Failed to delete scenario");$(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(Fe){console.error("[EntityDetail] Error deleting scenario:",Fe),be(Fe instanceof Error?Fe.message:"Failed to delete scenario"),we(!1)}finally{re(!1)}},kr=h&&c&&h.entitySha!==c.sha,rn=c?EC(c):!1;return n(To,{children:d("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:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:R,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:c==null?void 0:c.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:c==null?void 0:c.filePath,children:c==null?void 0:c.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:T.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(ge=>n(ke,{to:rs(ge.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${O===ge.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:O===ge.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[ge.label,ge.count!==void 0&&ge.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${O===ge.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ge.count})]})},ge.id))})]})}),(g||kr&&!p||v&&rn)&&!A&&!wr&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:d("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:kr&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":kr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&b?n(ke,{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:ge=>{ge.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ge=>{ge.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:ns,disabled:ft.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:ge=>{ft.state==="idle"&&(ge.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ge=>{ft.state==="idle"&&(ge.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[O==="scenarios"&&d(ve,{children:[Q&&E?n(jC,{scenario:E,entitySha:(c==null?void 0:c.sha)||"",onApply:gt,onSave:Cr,onEditMockData:Oo,onDelete:Lo,isApplying:V,isSaving:B,saveMessage:ne,showDeleteConfirm:ue,onShowDeleteConfirm:we,isDeleting:Z,deleteError:je}):n(_C,{scenarios:T,hiddenScenarios:_,analysis:h,selectedScenario:E,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:br,activeTab:O,entityType:c==null?void 0:c.entityType,entity:c,queueState:S,processIsRunning:z,isEntityAnalyzing:A,areScenariosStale:L,viewMode:I,setViewMode:Xe,isBreakdownView:i==="breakdown",onCreateScenario:Sr}),Un?d("div",{className:"flex flex-col flex-1 min-h-0",children:[d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:"Create New Scenario"}),n("button",{onClick:()=>Ft(!1),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",children:"Close"})]}),n("div",{className:"flex-1 min-h-0",children:n(qt,{prompt:dt,height:"100%",hideHeader:!0})})]}):i==="breakdown"?n(AC,{analysis:h??null,entitySha:(c==null?void 0:c.sha)||"",onCreateScenario:Sr}):Q&&E?n(Mo,{scenarioId:E.id||E.name,scenarioName:E.name,iframeUrl:ie,isStarting:he,isLoading:Te,showIframe:xe,iframeKey:Oe,onIframeLoad:Je,projectSlug:m,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[E&&d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:E.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Jt," × ",ts]})]}),d("div",{className:"flex items-center gap-2",children:[n(ke,{to:`/entity/${c==null?void 0:c.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"}),d("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"]}),d(ke,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${E.id}/dev`,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:"Dev Mode - Live preview with data editor and code sync",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),d(ke,{to:`/entity/${c==null?void 0:c.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(_p,{selectedScenario:E,analysis:h,entity:c,viewMode:I,cacheBuster:br,hasScenarios:T.length>0,isAnalyzing:Le,projectSlug:m,hasAnApiKey:C,processIsRunning:z,queueState:S})]})]}),O==="related"&&n($C,{relatedEntities:f}),O==="data"&&n(IC,{entity:c,analysis:h,scenarios:T,onAnalyze:ns}),O==="code"&&n(YC,{entity:c,entityCode:y}),O==="history"&&n(TC,{entity:c,history:N})]}),vr&&m&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Yn(!1),children:d("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:ge=>ge.stopPropagation(),children:[d("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:()=>Yn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(hn,{projectSlug:m,onClose:()=>Yn(!1)})})]})})]})})}),KC=Object.freeze(Object.defineProperty({__proto__:null,default:VC,loader:HC,meta:WC,shouldRevalidate:JC},Symbol.toStringTag,{value:"Module"}));async function GC(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:o,queue:a}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await We();const i=Ce();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),c=JSON.parse(await Ae.readFile(l,"utf8")),{projectSlug:u,branchId:p}=c;if(!u||!p)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${u}, Branch: ${p}`);const h=Qr(u);try{await Ae.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:m,branch:f}=await De(u);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await tt({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(v=>v.filePath).filter(v=>!!v))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const x=await Hg(m,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await pn({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:v=>{if(!v)return;const N=v.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&o0(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=a.enqueue({type:"analysis",commitSha:x.sha,projectSlug:u,filePaths:g,entityShas:t,entityNames:y.map(v=>v.name),...s?{context:s}:{},...o?{scenarioCount:o}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${b} for ${t.length} entities`),{jobId:b}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function qC({request:e,context:t}){if(e.method!=="POST")return le({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await en()),!r)return le({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("entitySha"),a=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),c=s.get("scenarioCount");let u;if(a)u=a.split(",").filter(Boolean);else if(o)u=[o];else return le({error:"Missing required field: entitySha or entityShas"},{status:400});if(u.length===0)return le({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${u.length} entity(ies)`);const p=await tt({shas:u}),m=[...new Set(p.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await GC({entityShas:u,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),le({success:!0,message:`Analysis queued for ${u.length} entity(ies)`,entityCount:u.length,fileCount:m,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),le({error:"Failed to start analysis",details:s.message},{status:500})}}const QC=Object.freeze(Object.defineProperty({__proto__:null,action:qC},Symbol.toStringTag,{value:"Module"}));function ZC(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:d("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:d("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 jp(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const o=t.getHours(),a=t.getMinutes(),i=o>=12?"pm":"am",l=o%12||12,c=a.toString().padStart(2,"0");return`Today, ${l}:${c} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function _t(e,t=[],r=!1){var p,h;if(t.some(m=>{var f,y;return!!((f=m.entityShas)!=null&&f.includes(e.sha)||(y=m.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const o=e.analyses[0];if(!(((p=o.status)==null?void 0:p.scenarios)&&o.status.scenarios.length>0&&o.status.scenarios.some(m=>m.screenshotFinishedAt||m.finishedAt))||o.entitySha!==e.sha)return"not-analyzed";const i=o.createdAt?new Date(o.createdAt).getTime():0,l=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,c=o.scenarios||[],u=c.some(m=>{var f,y,g;return((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=m.metadata)==null?void 0:g.executionResult)});return i>=l?c.length>0&&u?c.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":c.length>0?"incomplete":"not-analyzed":"out-of-date"}const XC=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function e2({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},o=await zn();return le({entities:o||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),le({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const t2=nt(function(){const t=lt(),r=t.entities,s=t.queueState;Yt({source:"simulations-page"});const[o,a]=P(""),[i,l]=P("visual"),c=pe(()=>{const g=[];return r.forEach(x=>{var v;const b=(v=x.analyses)==null?void 0:v[0];if(b!=null&&b.scenarios){const N=b.scenarios.filter(w=>{var C;return!((C=w.metadata)!=null&&C.sameAsDefault)}).map(w=>{var M,R,z,O,U;const C=(R=(M=w.metadata)==null?void 0:M.screenshotPaths)==null?void 0:R[0],S=(z=w.metadata)==null?void 0:z.noScreenshotSaved,k=C&&!S,T=(U=(O=b.status)==null?void 0:O.scenarios)==null?void 0:U.find(W=>W.name===w.name),_=T&&T.screenshotStartedAt&&!T.screenshotFinishedAt;let $;return k?$="completed":_?$="capturing":$="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:C||"",scenarioId:w.id,state:$}}).filter(w=>w.state==="completed"||w.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:b.createdAt||""})}}),g.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),u=pe(()=>r.filter(g=>{var v,N;const x=(v=g.analyses)==null?void 0:v[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(w=>{var C,S;return(S=(C=w.metadata)==null?void 0:C.screenshotPaths)==null?void 0:S[0]}))}),[r]),p=pe(()=>c.filter(({entity:g})=>{const x=!o||g.name.toLowerCase().includes(o.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[c,o,i]),h=pe(()=>u.filter(g=>{const x=!o||g.name.toLowerCase().includes(o.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[u,o,i]),m=ce(g=>{a(g.target.value)},[]),f=ce(g=>{l(g.target.value)},[]),y=c.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:d("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."})]})}),d("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"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative",children:[d("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(At,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:o,onChange:m})]})]})]}),y&&p.length>0&&n("div",{className:"mb-2",children:d("div",{className:"flex items-center py-3",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:p.length})," ",p.length===1?"entity":"entities"]}),d("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:d("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:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:p.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),d("div",{className:"flex flex-col gap-3",children:[y&&(p.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(ve,{children:p.map(({entity:g,screenshots:x})=>n(n2,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(g=>n(r2,{entity:g},g.sha)))]})]})})});function n2({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=zt(),o=Ke(),[a,i]=P(!1),l=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),c=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},u=()=>{i(!0),o.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};se(()=>{o.state==="idle"&&a&&i(!1)},[o.state,a]);const p=_t(e,r),h=ZC(p),m=p==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(St,{type:e.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[d(ke,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[m&&n(ve,{children:a||o.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(It,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:u,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 s(`/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=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(ut,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Wi,{size:"medium"}):null})}),d("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:d("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&&d(ve,{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 r2({entity:e}){const t=Ke(),[r,s]=P(!1),o=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return se(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:o,children:d("div",{className:"px-5 py-4 flex items-center",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(St,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-0.5",children:[n(ke,{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:jp(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?d("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(It,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:o,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const s2=Object.freeze(Object.defineProperty({__proto__:null,default:t2,loader:e2,meta:XC},Symbol.toStringTag,{value:"Module"}));function o2({request:e,context:t}){const r=t.dbNotifier||Nt;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 s=new ReadableStream({start(o){const a=new TextEncoder;o.enqueue(a.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
542
|
+
|
|
543
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(u);try{o.close()}catch{}}},c=p=>{try{o.enqueue(a.encode(`data: ${JSON.stringify({type:"db-change",changeType:p.type,timestamp:p.timestamp})}
|
|
544
|
+
|
|
545
|
+
`))}catch{l()}};r.on("change",c);const u=setInterval(()=>{try{o.enqueue(a.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
546
|
+
|
|
547
|
+
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const a2=Object.freeze(Object.defineProperty({__proto__:null,loader:o2},Symbol.toStringTag,{value:"Module"}));function i2(){return new Response(JSON.stringify({status:"ok",version:pi,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const l2=Object.freeze(Object.defineProperty({__proto__:null,loader:i2},Symbol.toStringTag,{value:"Module"}));function Vi(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],o=r[2],a={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?a.paths=i[1].split(`
|
|
548
|
+
`).filter(u=>u.trim().startsWith("-")).map(u=>u.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(a.paths=l[1].split(",").map(u=>u.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(a.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:a,body:o}}async function Do(e,t=""){const r=[];try{const s=await Ae.readdir(e,{withFileTypes:!0});for(const o of s){const a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){const i=await Do(ee.join(e,o.name),a);r.push(...i)}else o.isFile()&&o.name.endsWith(".md")&&r.push(a)}}catch{}return r}async function es(e){const t=await Do(e),r=[];for(const s of t){const o=ee.join(e,s);try{const a=await Ae.readFile(o,"utf-8"),{frontmatter:i,body:l}=Vi(a);r.push({filePath:s,absolutePath:o,frontmatter:i,body:l})}catch{}}return r}function Pp(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Ap(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Aa(e,s,{matchBase:!0}));const r=Pp(t);return r?Aa(e,r,{matchBase:!0}):!1}function c2(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Pp(e)?[]:t.filter(r=>Ap(r,e))}const d2=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Ki(e){const t=[];async function r(s,o){try{const a=await Pe.readdir(s,{withFileTypes:!0});for(const i of a){const l=G.join(s,i.name),c=o?`${o}/${i.name}`:i.name;i.isDirectory()&&d2.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const u2="codeyam-rule-state.json",wa=1;function Tp(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return dr.createHash("sha256").update(t).digest("hex")}function Mp(e){return ee.join(e,".claude",u2)}async function $p(e){const t=Mp(e);try{const r=await Ae.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==wa?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:wa,rules:{}}):s}catch{return{version:wa,rules:{}}}}async function Fp(e,t){const r=Mp(e),s=ee.dirname(r);await Ae.mkdir(s,{recursive:!0}),await Ae.writeFile(r,JSON.stringify(t,null,2)+`
|
|
549
|
+
`,"utf-8")}async function Gi(e,t){const r=await $p(e),s=new Set(t.map(o=>o.filePath));for(const o of Object.keys(r.rules))s.has(o)||delete r.rules[o];for(const o of t){const a=await Ae.readFile(o.absolutePath,"utf-8"),i=Tp(a),l=r.rules[o.filePath];l?l.contentHash!==i&&(r.rules[o.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[o.filePath]={contentHash:i,reviewed:!1}}return await Fp(e,r),r}async function Uc(e,t,r,s){const o=await $p(e);if(r){const a=ee.join(e,".claude","rules"),i=ee.join(a,t),l=await Ae.readFile(i,"utf-8"),c=Tp(l);o.rules[t]?(o.rules[t].reviewed=!0,o.rules[t].contentHash=c):o.rules[t]={contentHash:c,reviewed:!0}}else o.rules[t]&&(o.rules[t].reviewed=!1);await Fp(e,o)}function qi(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Rp(e,t=""){const r=[],s=await Ae.readdir(e,{withFileTypes:!0});for(const o of s){const a=t?`${t}/${o.name}`:o.name;o.isDirectory()?r.push(...await Rp(ee.join(e,o.name),a)):o.name.endsWith(".md")&&r.push(a)}return r}function no(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
550
|
+
`).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function p2({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),o=ee.join(t,".claude","rules");if(s==="recent-changes")return m2(t,o);if(s==="reviewed-status")return g2(t,o);if(s==="audit")return y2(t,o);if(s==="source-files")return x2(t);if(s==="rule-coverage")return b2(t,o);if(s==="rule-diff"){const a=r.searchParams.get("filePath");return a?f2(t,a):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const a=r.searchParams.get("path");return a?v2(o,a):Response.json({error:"Missing required parameter: path"},{status:400})}try{const a=await Do(o),i=[];for(const p of a){const h=ee.join(o,p);try{const m=await Ae.readFile(h,"utf-8"),f=await Ae.stat(h),{frontmatter:y,body:g}=Vi(m);i.push({filePath:p,content:m,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((p,h)=>new Date(h.lastModified).getTime()-new Date(p.lastModified).getTime());let l=i.length>0;if(!l)try{await Ae.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await es(o),u={};if(c.length>0){const p=await Gi(t,c);for(const h of c)u[h.filePath]=qi(p,h.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:u})}catch(a){return console.error("[API] Error loading memories:",a),Response.json({error:"Failed to load memories",details:a instanceof Error?a.message:String(a),memoryInitialized:!1},{status:500})}}async function h2(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const o of s.split(`
|
|
551
|
+
`).filter(Boolean)){const a=o.substring(0,2);let i=o.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=a[0],c=a[1];let u=[i];if(i.endsWith("/")&&l==="?"){const p=ee.join(e,i);try{u=(await Rp(p)).map(m=>i+m)}catch{continue}}for(const p of u){if(p.endsWith("/"))continue;const h=p.replace(".claude/rules/","");let m="modified";l==="A"||l==="?"?m="added":l==="D"||c==="D"?m="deleted":(l==="M"||c==="M")&&(m="modified");let f="";try{if(m==="deleted")f=t(`git diff HEAD -- "${p}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(m==="added"&&l==="?"){const y=`${e}/${p}`;try{const g=await Ae.readFile(y,"utf-8");f=`diff --git a/${p} b/${p}
|
|
552
|
+
new file mode 100644
|
|
553
|
+
--- /dev/null
|
|
554
|
+
+++ b/${p}
|
|
555
|
+
@@ -0,0 +1,${g.split(`
|
|
556
|
+
`).length} @@
|
|
557
|
+
${g.split(`
|
|
558
|
+
`).map(x=>"+"+x).join(`
|
|
559
|
+
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${p}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
560
|
+
... (truncated)`)}catch{f="(diff not available)"}m==="modified"&&no(f)||r.push({filePath:h,changeType:m,diff:f})}}}catch{}return r}async function m2(e,t){try{const{execSync:r}=await import("child_process"),s=[],o=await es(t),a={};if(o.length>0){const p=await Gi(e,o);for(const h of o)a[h.filePath]=qi(p,h.filePath)}const l=(await h2(e,r)).filter(p=>!a[p.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});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(`
|
|
561
|
+
`).filter(Boolean).slice(0,20);for(const p of u){const[h,m,...f]=p.split("|"),y=f.join("|");if(!h||!m)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const b of g.split(`
|
|
562
|
+
`).filter(Boolean)){const[v,N]=b.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const w=N.replace(".claude/rules/","");let C="modified";if(v==="A"?C="added":v==="D"&&(C="deleted"),a[w])continue;let S="";try{S=r(`git show ${h} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),S.length>5e3&&(S=S.substring(0,5e3)+`
|
|
563
|
+
... (truncated)`)}catch{S="(diff not available)"}C==="modified"&&no(S)||x.push({filePath:w,changeType:C,diff:S})}x.length>0&&s.push({commitHash:h.substring(0,8),date:m,message:y,files:x})}return Response.json({changes:s,reviewedStatus:a})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function f2(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,o=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),a=parseInt(o.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(no(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
|
|
564
|
+
... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:a}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await Ae.readFile(g,"utf-8"),b=`diff --git a/${s} b/${s}
|
|
565
|
+
new file mode 100644
|
|
566
|
+
--- /dev/null
|
|
567
|
+
+++ b/${s}
|
|
568
|
+
@@ -0,0 +1,${x.split(`
|
|
569
|
+
`).length} @@
|
|
570
|
+
${x.split(`
|
|
571
|
+
`).map(v=>"+"+v).join(`
|
|
572
|
+
`)}`;return Response.json({diff:{diff:b.length>5e3?b.substring(0,5e3)+`
|
|
573
|
+
... (truncated)`:b,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const u=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!u)return Response.json({diff:null});const[p,h,...m]=u.split("|"),f=m.join("|");if(!p||!h)return Response.json({diff:null});let y=r(`git show ${p} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?no(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
|
|
574
|
+
... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:h,isUncommitted:!1,commitCount:a}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function g2(e,t){try{const r=await es(t),s={};if(r.length>0){const o=await Gi(e,r);for(const a of r)s[a.filePath]=qi(o,a.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function y2(e,t){try{const r=await es(t),s=await Ki(e),o=[];for(const a of s){const i=r.filter(l=>Ap(a,l));if(i.length>0){const l=i.reduce((c,u)=>c+u.body.length,0);o.push({filePath:a,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.body.length})),totalTextLength:l})}}return o.sort((a,i)=>i.totalTextLength-a.totalTextLength),Response.json({topPaths:o,totalFilesWithCoverage:o.length,allSourceFiles:s})}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 x2(e){try{const t=await Ki(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 b2(e,t){try{const[r,s]=await Promise.all([es(t),Ki(e)]),o={};for(const a of r)o[a.filePath]=c2(a,s).length;return Response.json({coverage:o})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function v2(e,t){try{const r=await Do(e),s=[];for(const a of r){const i=ee.join(e,a);try{const l=await Ae.readFile(i,"utf-8"),c=await Ae.stat(i),{frontmatter:u,body:p}=Vi(l);u.paths&&u.paths.some(h=>Aa(t,h,{matchBase:!0}))&&s.push({filePath:a,content:l,frontmatter:u,body:p,lastModified:c.mtime.toISOString()})}catch{}}const o=s.reduce((a,i)=>a+i.body.length,0);return Response.json({rules:s,totalTextLength:o})}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 w2({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:o,filePath:a,content:i,lastModified:l}=s;if(!a)return Response.json({error:"Missing required field: filePath"},{status:400});if(o==="mark-reviewed")return await Uc(t,a,!0),console.log(`[API] Rule marked as reviewed: ${a}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:a});if(o==="mark-unreviewed")return await Uc(t,a,!1),console.log(`[API] Rule marked as unreviewed: ${a}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:a});const c=ee.normalize(a);if(c.includes("..")||ee.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const u=ee.join(r,c);switch(o){case"create":case"update":return i?(await Ae.mkdir(ee.dirname(u),{recursive:!0}),await Ae.writeFile(u,i,"utf-8"),console.log(`[API] Memory ${o}d: ${a}`),Response.json({success:!0,message:`Memory ${o}d successfully`,filePath:a})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await Ae.unlink(u),console.log(`[API] Memory deleted: ${a}`);const p=ee.dirname(u);try{(await Ae.readdir(p)).length===0&&p!==r&&await Ae.rmdir(p)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(p){if(p.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw p}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const N2=Object.freeze(Object.defineProperty({__proto__:null,action:w2,loader:p2},Symbol.toStringTag,{value:"Module"}));async function S2({request:e,context:t}){var a;let r=t.analysisQueue;if(r||(r=await en()),!r)return le({error:"Queue not initialized"},{status:500});const s=new URL(e.url),o=s.searchParams.get("queryType");if(!o)return le({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const i=s.searchParams.get("jobId");if(!i)return le({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((a=l.currentlyExecuting)==null?void 0:a.id)===i)return le({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(p=>p.id===i);if(c){const p=l.jobs.indexOf(c);return le({jobId:i,status:"queued",position:p,job:c})}const u=r.getJobResult(i);return u?le({jobId:i,status:u.status==="error"?"failed":"completed",error:u.error}):le({jobId:i,status:"completed"})}if(o==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async u=>{const p=[];if(u.entityShas&&u.entityShas.length>0){const h=u.entityShas.map(f=>In(f)),m=await Promise.all(h);p.push(...m.filter(f=>f!==null))}return{id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:p,filePaths:u.filePaths}}));let c;if(i.currentlyExecuting){const u=i.currentlyExecuting,p=[];if(u.entityShas&&u.entityShas.length>0){const h=u.entityShas.map(f=>In(f)),m=await Promise.all(h);p.push(...m.filter(f=>f!==null))}c={id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:p,filePaths:u.filePaths}}return le({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return le({error:"Unknown queryType"},{status:400})}async function C2({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 en(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),le({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:o,...a}=s;if(console.log("[Queue API] Action:",o,"Params:",Object.keys(a)),o==="enqueue"){const{jobId:i,completion:l}=r.enqueue(a);return l.catch(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),le({jobId:i,status:"queued"})}if(o==="resume")return r.resume(),le({status:"resumed"});if(o==="pause")return r.pause(),le({status:"paused"});if(o==="remove"){const{jobId:i}=a;return i?r.removeJob(i)?le({status:"removed",jobId:i}):le({error:"Job not found in queue"},{status:404}):le({error:"Missing jobId parameter"},{status:400})}if(o==="clear"){const i=r.clearQueue();return le({status:"cleared",count:i})}if(o==="reorder"){const{jobId:i,direction:l}=a;return!i||!l?le({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?le({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?le({status:"reordered",jobId:i,direction:l}):le({error:"Could not reorder job (not found or at boundary)"},{status:400})}return le({error:"Unknown action"},{status:400})}const k2=Object.freeze(Object.defineProperty({__proto__:null,action:C2,loader:S2},Symbol.toStringTag,{value:"Module"})),E2=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],_2=nt(function(){return Ke(),n(To,{children:d("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:d("div",{className:"flex items-center h-full px-6 gap-6",children:[d("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"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[d("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"})]}),d("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:d("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[d("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"})]}),d("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"})]})}),d("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(_p,{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})]})]})})}),j2=Object.freeze(Object.defineProperty({__proto__:null,default:_2,meta:E2},Symbol.toStringTag,{value:"Module"})),P2=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function A2({request:e}){var t,r;try{const s=await go();if(!s)return le({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let o=!1;try{const c=await Ye();if(c){const{project:u}=await De(c);o=((r=(t=u.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const a=Ce()||process.cwd(),i=await yo(a),l=cu(s.projectSlug);return le({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:o,error:null})}catch(s){return console.error("Failed to load config:",s),le({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function T2(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function M2({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),o=t.get("groqApiKey"),a=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),c=t.get("memorySettings");let u;if(r)try{u=JSON.parse(r)}catch{return le({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let p;if(s)try{p=JSON.parse(s)}catch{return le({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;l&&(h=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let m;if(c)try{m=JSON.parse(c)}catch{return le({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(p){const x=await go();x!=null&&x.webapps&&(f=x.webapps.map((b,v)=>{if(p[v]!==void 0){const N=T2(p[v]);return{...b,startCommand:N}}return b}))}if(!await tu({universalMocks:u,pathsToIgnore:h,webapps:f,memory:m}))return le({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(o!==void 0||a!==void 0||i!==void 0){const x=Ce()||process.cwd(),b=await yo(x);g=o!==void 0&&o!==(b.GROQ_API_KEY||"")||a!==void 0&&a!==(b.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(b.OPENAI_API_KEY||""),await qg(x,{...b,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:a||void 0,OPENAI_API_KEY:i||void 0},!0)}return le({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),le({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Wc(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Jc({mock:e,onSave:t,onCancel:r}){const[s,o]=P(e.entityName),[a,i]=P(e.filePath),[l,c]=P(e.content);return d("div",{className:"space-y-3",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:p=>o(p.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"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:a,onChange:p=>i(p.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"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:p=>c(p.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' }"})]}),d("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(!s.trim()||!a.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:a,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function $2(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const F2=nt(function(){var je,be,Ee,X,fe;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:o,error:a}=lt(),i=Fh(),l=Ke(),c=Bt(),[u,p]=P(o?"project-metadata":"memory");Yt({source:"settings-page"});const[h,m]=P((t==null?void 0:t.universalMocks)||[]),[f,y]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,v]=P((r==null?void 0:r.GROQ_API_KEY)||""),[N,w]=P((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,S]=P((r==null?void 0:r.OPENAI_API_KEY)||""),[k,T]=P(!1),[_,$]=P(!1),[M,R]=P(!1),[z,O]=P(!1),[U,W]=P(!1),[J,j]=P(!1),[D,A]=P(null),[L,E]=P(!1),[F,I]=P({}),[K,Q]=P(((je=t==null?void 0:t.memory)==null?void 0:je.conversationReflection)??!0),[V,Y]=P(((be=t==null?void 0:t.memory)==null?void 0:be.ruleMaintenance)??!0),[B,H]=P(((Ee=t==null?void 0:t.memory)==null?void 0:Ee.promptModel)??"haiku");se(()=>{var ae,ie,he,Te;if(t){m(t.universalMocks||[]);const xe=(t.pathsToIgnore||[]).join(", ");y(xe),x(xe);const Oe={};(ae=t.webapps)==null||ae.forEach((Je,bt)=>{Je.startCommand&&(Oe[bt]=Wc(Je.startCommand))}),I(Oe),Q(((ie=t.memory)==null?void 0:ie.conversationReflection)??!0),Y(((he=t.memory)==null?void 0:he.ruleMaintenance)??!0),H(((Te=t.memory)==null?void 0:Te.promptModel)??"haiku")}r&&(v(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),S(r.OPENAI_API_KEY||""))},[t,r]),se(()=>{if(i!=null&&i.success){O(!0);const ae=setTimeout(()=>O(!1),3e3);return()=>clearTimeout(ae)}},[i]),se(()=>{if(l.state==="idle"&&l.data&&!J){console.log("[Settings] Fetcher data:",l.data);const ae=l.data;if(ae.success){console.log("[Settings] Save successful, revalidating..."),O(!0),j(!0),(f!==g||ae.requiresRestart)&&W(!0),c.revalidate();const ie=setTimeout(()=>{O(!1),j(!1)},3e3);return()=>clearTimeout(ie)}}},[l.state,l.data,J,c,f,g]);const ne=ae=>{ae.preventDefault();const ie=new FormData(ae.currentTarget);ie.set("universalMocks",JSON.stringify(h)),ie.set("startCommands",JSON.stringify(F)),ie.set("memorySettings",JSON.stringify({conversationReflection:K,ruleMaintenance:V,promptModel:B})),console.log("[Settings] Submitting form data:",{universalMocks:ie.get("universalMocks"),startCommands:ie.get("startCommands"),openAiApiKey:ie.get("openAiApiKey")?"***":"(empty)"}),l.submit(ie,{method:"post"})},oe=ae=>{m([...h,ae]),E(!1)},Z=(ae,ie)=>{const he=[...h];he[ae]=ie,m(he),A(null)},re=ae=>{m(h.filter((ie,he)=>he!==ae))};if(a)return d("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:a})})]});const ue=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],we=o?ue:ue.filter(ae=>ae.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[d("div",{className:"mb-8 flex justify-between items-start",children:[d("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:l.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:l.state==="submitting"?"Saving...":"Save Settings"})]}),(z||U||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&d("div",{className:"mb-4 space-y-3",children:[z&&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!"}),U&&d("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:"}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(xt,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const ae=l.data;return typeof ae.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:ae.error}):null}return null})()]}),d("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:we.map(ae=>n("li",{children:n("button",{type:"button",onClick:()=>p(ae.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${u===ae.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:ae.label})},ae.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:ne,className:"space-y-6",children:[u==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("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((ae,ie)=>{var he;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ae.path==="."?"Root":ae.path})]}),ae.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ae.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ae.framework})]}),ae.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",d("span",{className:"text-gray-900 font-mono text-xs",children:[ae.startCommand.command," ",(he=ae.startCommand.args)==null?void 0:he.join(" ")]})]})]})},ie)})}):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`."})]})]}),u==="ai-provider"&&d("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."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:ae=>v(ae.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:()=>T(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:k?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:_?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:N,onChange:ae=>w(ae.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:()=>$(!_),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:_?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:M?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:ae=>S(ae.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:()=>R(!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"})]})]})]})]})]}),u==="commands"&&d("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((ae,ie)=>d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[d("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:ae.path==="."?"Root":ae.path}),n("div",{className:"text-sm text-gray-600",children:ae.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${ie}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ie}`,name:`startCommand-${ie}`,value:F[ie]||"",onChange:he=>I({...F,[ie]:he.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"})]})]},ie))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),u==="paths-to-ignore"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:ae=>y(ae.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"}),d("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"})]})]}),u==="universal-mocks"&&d("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"}),h.length===0?d("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>E(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((ae,ie)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:D===ie?n(Jc,{mock:ae,onSave:he=>Z(ie,he),onCancel:()=>A(null)}):n(ve,{children:d("div",{className:"flex justify-between items-start mb-2",children:[d("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:ae.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:ae.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:ae.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>A(ie),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:()=>re(ie),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ie))}),h.length>0&&n("button",{type:"button",onClick:()=>E(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),u==="memory"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":K,onClick:()=>Q(!K),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${K?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${K?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":V,onClick:()=>Y(!V),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${V?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${V?"translate-x-5":"translate-x-0"}`})})]})}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(ae=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${B===ae.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:ae.value,checked:B===ae.value,onChange:()=>H(ae.value),className:"mt-1 accent-[#005C75]"}),d("div",{children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:ae.label}),ae.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:ae.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:ae.description})]})]},ae.value))})]})]})]}),u==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("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:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("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&&d("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((ae,ie)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ae.path==="."?"Root":ae.path})]}),ae.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ae.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ae.framework})]}),ae.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Wc(ae.startCommand)})]})]})},ie))})]})]}),s&&d("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:d("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((X=s.templateVersion.gitCommit)==null?void 0:X.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",$2(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((fe=s.cachedAnalyzerVersion.gitCommit)==null?void 0:fe.slice(0,7))||"unknown"}),s.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"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&d("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"})]})]})})]})]})]})})]}),L&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("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(Jc,{mock:{entityName:"",filePath:"",content:""},onSave:oe,onCancel:()=>E(!1)})]})})]})})}),R2=Object.freeze(Object.defineProperty({__proto__:null,action:M2,default:F2,loader:A2,meta:P2},Symbol.toStringTag,{value:"Module"}));async function D2({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=Ce();if(!r)return new Response("Project root not found",{status:500});const o=ee.extname(t)!==""?t:`${t}.html`,a=ee.join(r,".codeyam","captures","static",o);try{await Ae.access(a);let i=await Ae.readFile(a);const l=ee.extname(a).toLowerCase();let c="application/octet-stream";if(l===".html"){c="text/html";let u=i.toString("utf-8");const p=u.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(p)try{const m=p[1].match(/=\s*(\{[\s\S]*\})/);if(m){const f=JSON.parse(m[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;u=u.replace(p[0],y)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(u,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const I2=Object.freeze(Object.defineProperty({__proto__:null,loader:D2},Symbol.toStringTag,{value:"Module"}));function O2(e,t,r=10){var c;const s=new Map,o=u=>u.entityType==="visual"||u.entityType==="library";for(const u of e)o(u)&&s.set(u.sha,{entity:u,depth:0});const a=new Map;for(const u of t){const p=(c=u.metadata)==null?void 0:c.importedBy;if(p)for(const h of Object.keys(p))for(const m of Object.keys(p[h])){const{shas:f}=p[h][m];for(const y of f)a.has(u.sha)||a.set(u.sha,new Set),a.get(u.sha).add(y)}}const i=[],l=new Set;for(const u of e)i.push({sha:u.sha,depth:0}),l.add(u.sha);for(;i.length>0;){const{sha:u,depth:p}=i.shift();if(p>=r)continue;const h=a.get(u);if(h)for(const m of h){if(l.has(m))continue;l.add(m);const f=t.find(y=>y.sha===m);if(f){if(o(f)){const y=p+1,g=s.get(m);(!g||y<g.depth)&&s.set(m,{entity:f,depth:y})}i.push({sha:m,depth:p+1})}}}return Array.from(s.values()).sort((u,p)=>u.depth!==p.depth?u.depth-p.depth:u.entity.name.localeCompare(p.entity.name))}function ro(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const o=s.sort((a,i)=>{var u,p;const l=((u=a.metadata)==null?void 0:u.editedAt)||a.createdAt||"";return(((p=i.metadata)==null?void 0:p.editedAt)||i.createdAt||"").localeCompare(l)});r.push(o[0])}return r}function Dp(e,t){const r=new Map,s=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&s.add(o.oldPath);for(const o of e){const a=t.filter(c=>c.filePath===o.path||o.status==="renamed"&&o.oldPath&&c.filePath===o.oldPath),i=a.filter(c=>{var u,p;return s.has(c.filePath)&&((u=c.metadata)==null?void 0:u.isUncommitted)&&!((p=c.metadata)!=null&&p.isSuperseded)}),l=ro(i);r.set(o.path,{status:o,entities:a,editedEntities:l})}return r}function L2(e,t,r){const s=new Map;if(!r){for(const a of e)if(a.status==="deleted")s.set(a.path,{status:a,entities:[]});else{const i=t.filter(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),l=ro(i);s.set(a.path,{status:a,entities:l})}return s}const o=new Map;for(const a of r.fileComparisons){const i=new Set;for(const l of a.newEntities)i.add(l.name);for(const l of a.modifiedEntities)i.add(l.name);for(const l of a.deletedEntities)i.add(l.name);i.size>0&&o.set(a.filePath,i)}for(const a of e){const i=o.get(a.path);if(a.status==="deleted")s.set(a.path,{status:a,entities:[]});else{const l=i?t.filter(u=>(u.filePath===a.path||a.status==="renamed"&&a.oldPath&&u.filePath===a.oldPath)&&i.has(u.name)):[],c=ro(l);s.set(a.path,{status:a,entities:c})}}return s}function z2(e,t){const r=new Map,s=Ip(e,t);for(const o of s){const i=O2([o],t).filter(({depth:l})=>l>0);r.set(o.sha,i)}return r}function Ip(e,t){const r=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&r.add(o.oldPath);const s=t.filter(o=>{var a,i;return r.has(o.filePath)&&((a=o.metadata)==null?void 0:a.isUncommitted)&&!((i=o.metadata)!=null&&i.isSuperseded)});return ro(s)}function B2({recentSimulations:e}){const t=pe(()=>{const r=new Map;return e.forEach(s=>{const o=s.entitySha,a=r.get(o);a?a.push(s):r.set(o,[s])}),Array.from(r.entries()).map(([s,o])=>({entitySha:s,entityName:o[0].entityName,scenarios:o}))},[e]);return d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("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?d(ve,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>d("div",{children:[d("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(Br,{size:16,style:{color:"#8B5CF6"}})}),n(ke,{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((s,o)=>n(ke,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.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:a=>{a.currentTarget.style.borderColor="#005C75",a.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="#E5E7EB",a.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(ut,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${o}`))})]},r.entitySha))}),n(ke,{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 →"})]}):d("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(Br,{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."}),d("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(ke,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(ke,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Y2="/assets/codeyam-name-logo-CvKwUgHo.svg",U2=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function W2({request:e,context:t}){var r,s,o,a,i;try{const l=await Ye();if(l){const{project:z}=await De(l),O=((r=z.metadata)==null?void 0:r.editorMode)??!1;if(!(((o=(s=z.metadata)==null?void 0:s.labs)==null?void 0:o.simulations)??!1)||O)return Rh("/memory")}const c=t.analysisQueue,u=c?c.getState():{paused:!1,jobs:[]},[p,h]=await Promise.all([zn(),hr()]),m=gr(),f=p?Dp(m,p):new Map,y=Array.from(f.entries()).sort((z,O)=>z[0].localeCompare(O[0])),g=(p==null?void 0:p.length)||0,x=(p==null?void 0:p.filter(z=>z.entityType==="visual").length)||0,b=(p==null?void 0:p.filter(z=>z.entityType==="library").length)||0,v=p?Ip(m,p):[],N=v.length,w=(p==null?void 0:p.filter(z=>(z.analyses??[]).filter(O=>O.scenarios&&O.scenarios.length>0).length>0).length)||0,C=(p==null?void 0:p.reduce((z,O)=>{var W,J,j;const U=((j=(J=(W=O.analyses)==null?void 0:W[0])==null?void 0:J.scenarios)==null?void 0:j.length)||0;return z+U},0))||0,S=(p==null?void 0:p.reduce((z,O)=>{var J,j;const W=(((j=(J=O.analyses)==null?void 0:J[0])==null?void 0:j.scenarios)||[]).filter(D=>{var A,L;return(L=(A=D.metadata)==null?void 0:A.screenshotPaths)==null?void 0:L[0]}).length;return z+W},0))||0,k=[];p==null||p.forEach(z=>{var U;const O=(U=z.analyses)==null?void 0:U[0];O!=null&&O.scenarios&&O.scenarios.filter(J=>{var j;return!((j=J.metadata)!=null&&j.sameAsDefault)}).forEach(J=>{var D,A;const j=(A=(D=J.metadata)==null?void 0:D.screenshotPaths)==null?void 0:A[0];j&&k.push({entitySha:z.sha,entityName:z.name,scenarioId:J.id,scenarioName:J.name,screenshotPath:j,createdAt:O.createdAt||""})})}),k.sort((z,O)=>new Date(O.createdAt).getTime()-new Date(z.createdAt).getTime());const T=k.slice(0,16),_=(p==null?void 0:p.filter(z=>z.entityType==="visual").filter(z=>{var W,J;const O=(W=z.analyses)==null?void 0:W[0];return!((J=O==null?void 0:O.scenarios)==null?void 0:J.some(j=>{var D,A;return(A=(D=j.metadata)==null?void 0:D.screenshotPaths)==null?void 0:A[0]}))}).slice(0,8))||[],$=(a=h==null?void 0:h.metadata)==null?void 0:a.currentRun,M=((i=$==null?void 0:$.currentEntityShas)==null?void 0:i.length)||0,R=u.jobs.length||0;return le({stats:{totalEntities:g,visualEntities:x,libraryEntities:b,uncommittedEntities:N,entitiesWithAnalyses:w,totalScenarios:C,capturedScreenshots:S,currentlyAnalyzing:M,filesOnQueue:R},uncommittedFiles:y,uncommittedEntitiesList:v,recentSimulations:T,visualEntitiesForSimulation:_,projectSlug:l,queueState:u,currentCommit:h})}catch(l){return console.error("Failed to load dashboard data:",l),le({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 J2=nt(function(){var D,A;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:o,visualEntitiesForSimulation:a,projectSlug:i,queueState:l,currentCommit:c}=lt(),u=Ke(),p=Bt(),{showToast:h}=ai();Yt({source:"dashboard"});const[m,f]=P(new Set),[y,g]=P(null),[x,b]=P(!1),[v,N]=P(!1),{lastLine:w,isCompleted:C}=Qt(i,!!y),{simulatingEntity:S,scenarios:k,scenarioStatuses:T,allScenariosCaptured:_}=pe(()=>{var Y,B;const L={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return L;const E=a==null?void 0:a.find(H=>H.sha===y);if(!E)return L;const F=(Y=E.analyses)==null?void 0:Y[0],I=(F==null?void 0:F.scenarios)||[],K=((B=F==null?void 0:F.status)==null?void 0:B.scenarios)||[],Q=K.filter(H=>H.screenshotFinishedAt).length,V=I.length>0&&Q===I.length;return{simulatingEntity:E,scenarios:I,scenarioStatuses:K,allScenariosCaptured:V}},[y,a]);se(()=>{(C||_)&&g(null)},[C,_]);const $=(D=c==null?void 0:c.metadata)==null?void 0:D.currentRun,M=new Set(($==null?void 0:$.currentEntityShas)||[]),R=new Set(l.jobs.flatMap(L=>L.entityShas||[])),z=new Set(((A=l.currentlyExecuting)==null?void 0:A.entityShas)||[]),O=s.filter(L=>L.entityType==="visual"||L.entityType==="library"),U=O.filter(L=>!M.has(L.sha)&&!R.has(L.sha)&&!z.has(L.sha)),W=()=>{if(U.length===0){h("All entities are already queued or analyzing","info",3e3);return}const L=U.map(E=>E.sha);N(!0),h(`Starting analysis for ${U.length} entities...`,"info",3e3),u.submit({entityShas:L.join(",")},{method:"post",action:"/api/analyze"})};se(()=>{if(u.state==="idle"&&u.data){const L=u.data;L.success?(console.log("[Analyze All] Success:",L.message),h(`Analysis started for ${L.entityCount} entities in ${L.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):L.error&&(console.error("[Analyze All] Error:",L.error),h(`Error: ${L.error}`,"error",8e3),N(!1))}},[u.state,u.data,h]);const J=L=>{f(E=>{const F=new Set(E);return F.has(L)?F.delete(L):F.add(L),F})},j=[{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:d("div",{className:"px-20 pt-8 pb-12",children:[d("header",{className:"mb-8 flex justify-between items-center",children:[d("div",{className:"flex items-center gap-4",children:[n("img",{src:Y2,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,L=>L.toUpperCase()):"Project"})]}),p.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:j.map((L,E)=>n(ke,{to:L.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 ${L.color}`},children:d("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[d("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[d("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:L.label}),d("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:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[L.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:L.color},children:"View All →"})]}),d("div",{className:"flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-3",children:[d("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${L.color}15`},children:[L.iconType==="folder"&&n(cm,{size:20,style:{color:L.color}}),L.iconType==="check"&&n(qa,{size:20,style:{color:L.color}}),L.iconType==="image"&&n(Br,{size:20,style:{color:L.color}}),L.iconType==="code-xml"&&n(dm,{size:20,style:{color:L.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:L.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:L.color},children:"View All →"})]})]})},E))}),d("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[d("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[d("div",{className:"flex justify-between items-start mb-5",children:[d("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 ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),O.length>0&&n("button",{onClick:W,disabled:u.state!=="idle"||v||U.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:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:u.state!=="idle"||v?"Starting analysis...":U.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([L,E])=>{const F=m.has(L),I=E.editedEntities||[];return d("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(L),role:"button",tabIndex:0,children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:F?"▼":"▶"}),d("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[d("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"})})})]}),d("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:L}),d("span",{className:"text-xs text-gray-500",children:[I.length," entit",I.length!==1?"ies":"y"]})]})]})}),F&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:I.length>0?I.map(K=>{const Q=M.has(K.sha),V=R.has(K.sha)||z.has(K.sha);return d(ke,{to:`/entity/${K.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:Y=>Y.currentTarget.style.borderColor="#005C75",onMouseLeave:Y=>Y.currentTarget.style.borderColor="inherit",children:[d("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:K.entityType==="visual"?"#8B5CF615":K.entityType==="library"?"#6366F1":"#EC4899"},children:[K.entityType==="visual"&&n(Br,{size:16,style:{color:"#8B5CF6"}}),K.entityType==="library"&&n(_d,{size:16,className:"text-white"}),K.entityType==="other"&&n(um,{size:16,className:"text-white"})]}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:K.name}),K.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),K.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),K.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),K.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:K.description})]}),d("div",{className:"flex items-center gap-2 shrink-0",children:[Q&&d("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(It,{size:14,className:"animate-spin"}),"Analyzing..."]}),!Q&&V&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!Q&&!V&&n("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),h(`Starting analysis for ${K.name}...`,"info",3e3),u.submit({entityShas:K.sha},{method:"post",action:"/api/analyze"})},disabled:u.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:Y=>Y.currentTarget.style.backgroundColor="#004560",onMouseLeave:Y=>Y.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},K.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},L)})}):d("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:d("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(B2,{recentSimulations:o}),y&&d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:o.length>0?`Latest ${o.length} captured screenshot${o.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&d("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:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(St,{type:"visual"})}),d("div",{className:"flex-1 min-w-0",children:[d("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})]})]})}),_?d("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:"✅"}),d("span",{children:["Complete (",k.length," scenario",k.length!==1?"s":"",")"]})]}):w?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(It,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):u.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(It,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(It,{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((L,E)=>{var B,H,ne;const F=(B=S==null?void 0:S.analyses)==null?void 0:B[0],I=Ro(L,F==null?void 0:F.status,void 0,y||void 0,void 0),K=(ne=(H=L.metadata)==null?void 0:H.screenshotPaths)==null?void 0:ne[0],Q=I.isCaptured,V=I.status==="capturing"||I.status==="starting",Y=I.hasError;return Q?n(ke,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(ut,{screenshotPath:K,alt:L.name,title:L.name,className:"max-w-full max-h-full object-contain object-center"})},E):Y?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:I.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:`${V?"Capturing":"Pending"} ${L.name}...`,children:n("span",{className:V?"animate-pulse":"text-gray-400",children:V?"⋯":"⏹️"})},E)})})]})]})]}),x&&i&&n(hn,{projectSlug:i,onClose:()=>b(!1)})]})})}),H2=Object.freeze(Object.defineProperty({__proto__:null,default:J2,loader:W2,meta:U2},Symbol.toStringTag,{value:"Module"}));function Op({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Bm,{remarkPlugins:[Ym],components:{h1:({children:s})=>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:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:o})=>(o==null?void 0:o.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(ve,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:o})=>n("a",{href:o,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function Lp(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let o=t,a="";for(const i of s)a=a?`${a}/${i}`:i,o.children.has(i)||o.children.set(i,{name:i,path:a,memories:[],children:new Map}),o=o.children.get(i);s.length===0?t.memories.push(r):o.memories.push(r)}return t}function zp(e){let t=e.memories.length;for(const r of e.children.values())t+=zp(r);return t}function Io(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function zr(e){return Math.round(e/3.5)}function nr(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),u=Math.floor(c/(1e3*60)),p=Math.floor(c/(1e3*60*60));return u<3?"Just now":u<60?`${u}min ago`:p===1?"1h ago":`${p}h ago`}const o=t.toLocaleDateString("en-US",{month:"short"}),a=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${o} ${a}`:`${o} ${a}, ${i}`}function V2({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:o,onToggleReviewed:a,changeType:i,isUncommitted:l,changeDate:c,diff:u,isFadingOut:p,showLeftBorder:h}){const[m,f]=P(!1),[y,g]=P(!1),x=pe(()=>Io(e.body,e.filePath),[e.body,e.filePath]),b=zr(e.body.length),v=m?"#3e3e3e":l?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...p&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:N,style:w,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!m),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:v})})}),d("div",{className:"flex-1",children:[d("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"}),d("span",{className:"text-xs text-gray-400",children:["~",b.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&&d(ve,{children:[e.frontmatter.paths.slice(0,2).map((C,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:C},S)),e.frontmatter.paths.length>2&&d("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),d("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c&&n("span",{className:"text-xs text-gray-400",children:nr(c)}),a&&n("button",{onClick:C=>{C.stopPropagation(),a(e.filePath,e.lastModified,o??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${o?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:o?"Mark as unreviewed":"Mark as reviewed",children:o&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("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"&&u&&d("button",{onClick:C=>{C.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?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(Hs,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("button",{onClick:C=>{C.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(pm,{className:"w-3 h-3"}),"Edit"]}),d("button",{onClick:C=>{C.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(hm,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&u&&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:u.split(`
|
|
575
|
+
`).map((C,S)=>{let k="";return C.startsWith("+")&&!C.startsWith("+++")?k="text-green-400":C.startsWith("-")&&!C.startsWith("---")?k="text-red-400":C.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:C},S)})}),d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),d("div",{className:"flex items-center gap-2",children:[d("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(xt,{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&&d("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((C,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:C},S))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Op,{content:e.body})})]})]})}function K2(){return new Date().toISOString().split(".")[0]+"",`---
|
|
576
|
+
paths:
|
|
577
|
+
- '**/*.ts'
|
|
578
|
+
---
|
|
579
|
+
|
|
580
|
+
## Title
|
|
581
|
+
|
|
582
|
+
Description here.
|
|
583
|
+
`}function G2({rule:e,onSave:t,onCancel:r}){const[s,o]=P(e?`.claude/rules/${e.filePath}`:""),[a,i]=P((e==null?void 0:e.content)||K2()),[l,c]=P(!!e),[u,p]=P(!1),h=!e;return d("div",{className:"p-6",children:[d("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(cr,{className:"w-5 h-5"})})]}),h&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(Hs,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("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:"}),d("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),p(!0),setTimeout(()=>p(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:u?n(Mt,{className:"w-4 h-4 text-green-500"}):n(Ot,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!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)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:m=>o(m.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(s)},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(Ot,{className:"w-4 h-4"})})]})]}),e&&d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),d("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,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: \`${s}\``)},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(Ot,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:a,onChange:m=>i(m.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"})]}),d("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(s.replace(/^\.claude\/rules\//,""),a),disabled:!s.trim()||!a.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 q2({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:o}){const a=pe(()=>Lp(e),[e]),i=(u,p,h)=>{if(u.target.closest(".chevron-toggle")){h&&o(p||"root");return}const f=p||null;r(t===f?null:f),h&&!s.has(p||"root")&&o(p||"root")},l=u=>{r(t===u?null:u)},c=(u,p=0)=>{const h=s.has(u.path||"root"),m=zp(u),f=u.children.size>0,y=u.name==="root"?"(root)":u.name,g=u.memories.length>0||f,x=u.path||"",b=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${p*12+8}px`},onClick:v=>i(v,u.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:v=>{v.stopPropagation(),o(u.path||"root")},children:n(yn,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Pd,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${b?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),d("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[m," rules"]})]}),h&&d("div",{className:"relative",children:[(u.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${p*12+8+6}px`}}),u.memories.length>0&&n("div",{style:{paddingLeft:`${(p+1)*12+8}px`},children:u.memories.map(v=>{var w;const N=t===v.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(v.filePath),children:n("span",{className:"text-xs",children:(w=v.filePath.split("/").pop())==null?void 0:w.replace(".md","")})},v.filePath)})}),f&&n("div",{children:Array.from(u.children.values()).sort((v,N)=>v.name.localeCompare(N.name)).map(v=>c(v,p+1))})]})]},u.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(a)})}function Q2({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:o,reviewedStatus:a,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[u,p]=P({});se(()=>{p({})},[a]);const h=pe(()=>({...a,...u}),[a,u]),m=pe(()=>Lp(e),[e]),f=(g,x,b)=>{p(v=>({...v,[g]:!b})),b?l(g):i(g,x)},y=(g,x=0)=>{const b=s.has(g.path||"root"),v=g.children.size>0,N=g.name==="root"?"root":g.name,w=g.memories.length>0||v;return d("div",{children:[d("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:()=>w&&o(g.path||"root"),children:[w&&n(yn,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(Pd,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),b&&d("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||v)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(C=>n(V2,{rule:C,onEdit:t,onDelete:r,onView:c,isReviewed:h[C.filePath]??!1,onToggleReviewed:f},C.filePath))}),v&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((C,S)=>C.name.localeCompare(S.name)).map(C=>y(C,x+1))})]})]},g.path||"root")};return n("div",{children:y(m)})}function Z2({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[o,a]=P("unreviewed"),[i,l]=P("by-date"),[c,u]=P(null),[p,h]=P(!0),[m,f]=P(new Map),y=ye(t),g=ye([]);se(()=>()=>{g.current.forEach(clearTimeout)},[]),se(()=>{(async()=>{h(!0);try{const S=await(await fetch("/api/memory?action=rule-coverage")).json();u(S.coverage??null)}catch{u(null)}finally{h(!1)}})()},[s]),se(()=>{const w=y.current,C=[];for(const[S,k]of Object.entries(t))k&&!w[S]&&C.push(S);y.current=t,C.length!==0&&(f(S=>{const k=new Map(S);return C.forEach(T=>k.set(T,"approved")),k}),g.current.push(setTimeout(()=>{f(S=>{const k=new Map(S);return C.forEach(T=>k.set(T,"fading")),k})},1500)),g.current.push(setTimeout(()=>{f(S=>{const k=new Map(S);return C.forEach(T=>k.delete(T)),k})},2500)))},[t]);const x=pe(()=>{const w=[...e];return i==="by-impact"&&c!==null?w.sort((C,S)=>{const k=c[C.filePath]??0,T=c[S.filePath]??0;return T!==k?T-k:new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()}):w.sort((C,S)=>new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()),w},[e,i,c]),b=pe(()=>x.filter(w=>!t[w.filePath]).length,[x,t]),v=pe(()=>o==="unreviewed"?x.filter(w=>!t[w.filePath]||m.has(w.filePath)):x,[x,o,t,m]),N=!p&&c!==null;return d("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),d("button",{onClick:()=>a("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="unreviewed"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="unreviewed"?600:400,color:o==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",b,")"]})]}),d("button",{onClick:()=>a("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="all"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="all"?600:400,color:o==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),d("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),d("button",{onClick:()=>N&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(At,{className:"w-3 h-3"})]}),d("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(At,{className:"w-3 h-3"})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",d("span",{className:"relative group",children:[n(_a,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:v.map(w=>{const C=t[w.filePath]??!1,S=m.get(w.filePath),k=Io(w.body,w.filePath),T=(c==null?void 0:c[w.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${S==="fading"?"duration-1000":"duration-300"}`,style:{opacity:S==="fading"?0:1},children:d("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${S==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(w),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:k})}),n("span",{className:"text-xs text-center",children:p?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:T>0?"text-gray-700 font-medium":"text-gray-300",children:T}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:nr(w.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${C?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:C&&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"})})})})]})},w.filePath)})}),v.length===0&&o==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function X2(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
584
|
+
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
585
|
+
|
|
586
|
+
${r}
|
|
587
|
+
|
|
588
|
+
Please review these rules in conjunction with one another as they all apply to this file.
|
|
589
|
+
|
|
590
|
+
Review each rule with the other rules in mind:
|
|
591
|
+
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
592
|
+
- Efficiency: Are the rules concise and well-structured?
|
|
593
|
+
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
594
|
+
- Context window impact: Can the rules be shortened without losing important information?
|
|
595
|
+
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
596
|
+
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
597
|
+
|
|
598
|
+
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
599
|
+
|
|
600
|
+
Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function ek({filePath:e,rulePaths:t,onClose:r}){const[s,o]=P(!1),a=X2(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(cr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:a,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(a),o(!0),setTimeout(()=>o(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?d(ve,{children:[n(Mt,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(Ot,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function tk({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[o,a]=P("unreviewed"),[i,l]=P(null),[c,u]=P(""),[p,h]=P(0),[m,f]=P(!1),[y,g]=P(null),[x,b]=P(null),v=ye(null),N=ye(null),[w,C]=P({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[S,k]=P(!0);se(()=>{(async()=>{k(!0);try{const J=await(await fetch("/api/memory?action=audit")).json();C({topPaths:J.topPaths||[],totalFilesWithCoverage:J.totalFilesWithCoverage||0,allSourceFiles:J.allSourceFiles||[]})}catch(W){console.error("Failed to load audit data:",W)}finally{k(!1)}})()},[e]);const T=pe(()=>o==="all"?w.topPaths:w.topPaths.filter(U=>U.matchingRules.some(W=>!t[W.filePath])),[w.topPaths,o,t]);pe(()=>w.topPaths.filter(U=>U.matchingRules.some(W=>!t[W.filePath])).length,[w.topPaths,t]);const _=U=>U.split("/").pop()||U,$=pe(()=>{const U=new Map;for(const W of w.topPaths)U.set(W.filePath,W);return U},[w.topPaths]),M=pe(()=>{if(!c.trim())return[];const U=c.toLowerCase(),W=[],J=[];for(const j of w.allSourceFiles){const D=j.toLowerCase();if(!D.includes(U))continue;const A=$.get(j)||{filePath:j,matchingRules:[],totalTextLength:0};D.startsWith(U)?W.push(A):J.push(A)}return W.sort((j,D)=>j.filePath.localeCompare(D.filePath)),J.sort((j,D)=>j.filePath.localeCompare(D.filePath)),[...W,...J].slice(0,8)},[c,w.allSourceFiles,$]),R=ce(U=>{var W;g(U),l(U.filePath),u(U.filePath),f(!1),(W=v.current)==null||W.blur()},[]),z=ce(()=>{var U;u(""),g(null),l(null),(U=v.current)==null||U.focus()},[]),O=ce(U=>{var W;!m||M.length===0||(U.key==="ArrowDown"?(U.preventDefault(),h(J=>Math.min(J+1,M.length-1))):U.key==="ArrowUp"?(U.preventDefault(),h(J=>Math.max(J-1,0))):U.key==="Enter"?(U.preventDefault(),R(M[p])):U.key==="Escape"&&(f(!1),(W=v.current)==null||W.blur()))},[m,M,p,R]);return se(()=>{h(0)},[M]),d("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),d("div",{className:"relative flex-1 max-w-[300px]",children:[n(Kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:v,type:"text",value:c,onChange:U=>{u(U.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:O,placeholder:"Search files...",className:`w-full pl-8 ${c?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),c&&n("button",{type:"button",onMouseDown:U=>{U.preventDefault(),z()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),m&&M.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:M.map((U,W)=>d("div",{onMouseDown:J=>{J.preventDefault(),R(U)},onMouseEnter:()=>h(W),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${W===p?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Vs,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:U.filePath,children:(()=>{const J=U.filePath.toLowerCase().indexOf(c.toLowerCase());if(J===-1)return U.filePath;const j=U.filePath.slice(0,J),D=U.filePath.slice(J,J+c.length),A=U.filePath.slice(J+c.length);return d(ve,{children:[j,n("span",{className:"font-semibold text-[#005C75]",children:D}),A]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[U.matchingRules.length," rule",U.matchingRules.length!==1?"s":""]})]},U.filePath))})]}),n("div",{className:"flex-1"}),d("button",{onClick:()=>a("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="unreviewed"?600:400,color:o==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),d("button",{onClick:()=>a("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="all"?600:400,color:o==="all"?"#005C75":"#626262"},children:"All"})]})]}),d("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",d("span",{className:"relative group",children:[n(_a,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",d("span",{className:"relative group",children:[n(_a,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),S&&n("div",{className:"px-5 py-6",children:d("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"})]})}),!S&&(T.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...T.filter(W=>W.filePath!==y.filePath)].slice(0,8):T.slice(0,8)).map((U,W)=>{const J=U.matchingRules.length,j=U.matchingRules.filter(I=>!t[I.filePath]),D=j.length,A=j.reduce((I,K)=>I+K.bodyLength,0),L=D>0,E=i===U.filePath,F=(y==null?void 0:y.filePath)===U.filePath;return d("div",{children:[d("div",{onClick:()=>l(E?null:U.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${F?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[d("div",{className:"flex items-center gap-2 min-w-0",children:[E?n(At,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(yn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Vs,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:U.filePath,children:F?U.filePath:_(U.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:D}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:J})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:zr(A).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:zr(U.totalTextLength).toLocaleString()})]})]}),E&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[U.matchingRules.map(I=>{const K=r.find(V=>V.filePath===I.filePath),Q=t[I.filePath]??!1;return d("div",{onClick:V=>{V.stopPropagation(),K&&s(K)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Js,{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:K?Io(K.body,K.filePath):I.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[zr(I.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${Q?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:Q&&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"})})})]},I.filePath)}),d("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:I=>{I.stopPropagation(),b({filePath:U.filePath,rulePaths:U.matchingRules.map(K=>K.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},U.filePath)})}),!S&&T.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:o==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(ek,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>b(null)})]})}function nk({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:o,onDelete:a,onClose:i}){const l=Io(e.body,e.filePath),c=zr(e.body.length),u=e.frontmatter.category,p=`.claude/rules/${e.filePath}`,[h,m]=P(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return se(()=>{m(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&m(y.diff)}).catch(()=>{})},[e.filePath]),se(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[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:d("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"min-w-0 flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&d(ve,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:nr(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),u&&d("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:u})]}),d("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:p}),n(xt,{content:p,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),d("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",c.toLocaleString()]})]}),d("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[d("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(Mt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:o,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:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(cr,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),b=x.pop()||y,v=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Vs,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("span",{children:[v&&n("span",{className:"text-gray-500",children:v}),n("span",{className:"font-bold text-gray-900",children:b})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:d("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?nr(t.date):h!=null&&h.date?nr(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",nr(h.date)]}),n("pre",{className:"mt-2 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.diff.split(`
|
|
601
|
+
`).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),d("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Op,{content:e.body})})]})]})})}function rk(){return d("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 sk(){return d("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function ok(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[d("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),d("ol",{className:"space-y-5",children:[d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),d("div",{children:[d("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Hc,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),d("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),d("div",{className:"space-y-6",children:[d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[d("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),d("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Hc,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function Hc({value:e}){const[t,r]=P(!1);return d("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(Mt,{className:"w-3.5 h-3.5 text-green-400"}):d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function Ms({label:e,count:t,icon:r,bgColor:s,iconBgColor:o,textColor:a}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:d("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:o},children:r}),d("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:a},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:a},children:e})]})]})})}function ak({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:o}){return d("div",{className:"mb-8",children:[d("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[d("div",{children:[d("div",{className:"flex items-center gap-3 mb-2",children:[n(rk,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),d("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),d("div",{className:"flex items-center gap-3",children:[d("div",{className:"relative",children:[n(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:a=>t(a.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"})]}),d("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Qa,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(Ms,{label:"Total Rules",count:o.total,icon:n(sk,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Ms,{label:"Unreviewed",count:o.unreviewed,icon:n(mm,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Ms,{label:"Reviewed",count:o.reviewed,icon:n(Mt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Ms,{label:"Stale",count:o.stale,icon:n(jd,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function ik({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(cr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),d("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[d("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:d("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Qa,{className:"w-4 h-4"}),"New Rule"]})})]})})}function lk({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:d("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?"}),d("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Vc="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",Kc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Gc({text:e}){const[t,r]=P(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(ve,{children:[n(Mt,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(Ot,{className:"w-4 h-4"}),"Copy Prompt"]})})}function ck({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(cr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:Vc,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Gc,{text:Vc})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Kc,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Gc,{text:Kc})})]})]})})}function dk(){const[e,t]=P(!1);return d(ve,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(ck,{onClose:()=>t(!1)})]})}function uk(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
|
|
602
|
+
|
|
603
|
+
${e.map(r=>`- \`.claude/rules/${r}\``).join(`
|
|
604
|
+
`)}
|
|
605
|
+
|
|
606
|
+
Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts \`folder1/folder2/file1\` and \`folder1/folder2/folder3/file2\` then the rule should be in \`.claude/rules/folder1/folder2\`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!`}const qc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Qc({text:e}){const[t,r]=P(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(ve,{children:[n(Mt,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(Ot,{className:"w-4 h-4"}),"Copy Prompt"]})})}function pk({onClose:e,unreviewedRulePaths:t}){const r=uk(t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(cr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit Unreviewed Rules"}),d("p",{className:"text-gray-600 text-sm mb-4",children:["Claude will review only the ",t.length," unreviewed"," ",t.length===1?"rule":"rules"," for quality, relevance, and organization."]}),n("textarea",{readOnly:!0,value:r,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Qc,{text:r})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:qc,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Qc,{text:qc})})]})]})})}function hk({unreviewedRulePaths:e}){const[t,r]=P(!1);return e.length===0?d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3 opacity-50",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),n("p",{className:"text-sm text-gray-500",children:"All rules have been reviewed."})]}):d(ve,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),d("p",{className:"text-sm text-gray-500",children:["Ask Claude to review the ",e.length," unreviewed"," ",e.length===1?"rule":"rules","."]}),n("button",{onClick:()=>r(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),t&&n(pk,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const mk=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function fk({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?le({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?le({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):le({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),le({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const gk=nt(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:o}=lt(),a=Ke(),i=Bt(),[l,c]=P(""),[u,p]=P(null),[h,m]=P(new Set(["root"])),[f,y]=P(null),[g,x]=P(!1),[b,v]=P(null),[N,w]=P(0),[C,S]=P(!1),[k,T]=P(null),[_,$]=P(null),[M,R]=P({}),z=V=>{m(Y=>{const B=new Set(Y);return B.has(V)?B.delete(V):B.add(V),B})};Yt({source:"memory-page"});const O=pe(()=>({...r,...M}),[r,M]),U=ye(a.state);se(()=>{const V=U.current==="loading"||U.current==="submitting",Y=a.state==="idle";V&&Y&&a.data&&(i.revalidate(),y(null),x(!1),w(B=>B+1)),U.current=a.state},[a.state,a.data,i]),se(()=>{R(V=>{const Y={};for(const[B,H]of Object.entries(V))r[B]!==H&&(Y[B]=H);return Object.keys(Y).length===Object.keys(V).length?V:Y})},[r]);const W=(V,Y)=>{R(B=>({...B,[V]:!0})),a.submit({action:"mark-reviewed",filePath:V,lastModified:Y},{method:"POST",action:"/api/memory",encType:"application/json"})},J=V=>{R(Y=>({...Y,[V]:!1})),a.submit({action:"mark-unreviewed",filePath:V},{method:"POST",action:"/api/memory",encType:"application/json"})},j=(V,Y)=>{T(V),$(Y??null)},D=pe(()=>{let V=t;if(l.trim()){const Y=l.toLowerCase();V=V.filter(B=>{var ne;return(((ne=B.filePath.split("/").pop())==null?void 0:ne.replace(".md",""))||"").toLowerCase().includes(Y)||B.body.toLowerCase().includes(Y)})}return V},[t,l]),A=pe(()=>u?D.some(Y=>Y.filePath===u)?D.filter(Y=>Y.filePath===u):D.filter(Y=>Y.filePath.startsWith(u+"/")||Y.filePath===u):D,[D,u]),L=(V,Y)=>{const B=f?"update":"create";a.submit({action:B,filePath:V,content:Y},{method:"POST",action:"/api/memory",encType:"application/json"})},E=V=>{a.submit({action:"delete",filePath:V.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),v(null)},F=pe(()=>{const V=t.filter(Y=>O[Y.filePath]).length;return{total:t.length,reviewed:V,unreviewed:t.length-V,stale:0}},[t,O]),I=pe(()=>{const V=new Set(["root"]);for(const Y of D){const B=Y.filePath.split("/");B.pop();let H="";for(const ne of B)H=H?`${H}/${ne}`:ne,V.add(H)}return V},[D]),K=I.size===h.size&&[...I].every(V=>h.has(V)),Q=()=>{m(K?new Set(["root"]):new Set(I))};return o?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:o})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(ak,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>S(!0),reviewCounts:F}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:V=>V.stopPropagation(),children:n(G2,{rule:f,onSave:L,onCancel:()=>{x(!1),y(null)}})})}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(Z2,{memories:D,reviewedStatus:O,onViewRule:j,refreshKey:N}),n(tk,{onEditRule:y,onDeleteRule:v,refreshKey:N,reviewedStatus:O,onMarkReviewed:W,onMarkUnreviewed:J,memories:t,onViewRule:j})]}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(hk,{unreviewedRulePaths:t.filter(V=>!O[V.filePath]).map(V=>V.filePath)}),n(dk,{})]}),d("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:I.size>1&&n("button",{onClick:Q,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:K?"Collapse All":"Expand All"})})]}),d("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(q2,{memories:D,selectedPath:u,onSelectPath:p,expandedFolders:h,onToggleFolder:z})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(fm,{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"}),d("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),d("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(Qa,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[u&&d("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:u||"(root)"}),n("button",{onClick:()=>p(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Q2,{memories:A,onEdit:y,onDelete:v,expandedFolders:h,onToggleFolder:z,reviewedStatus:O,onMarkReviewed:W,onMarkUnreviewed:J,onViewRule:j})]})})]}),n("div",{className:"mt-8 mb-8",children:n(ke,{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:d("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:d("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"})]})}),d("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"})]})]})})}),k&&!f&&(()=>{const V=t.find(Y=>Y.filePath===k.filePath)??k;return n(nk,{rule:V,changeInfo:_??void 0,isReviewed:O[V.filePath]??!1,onApprove:()=>{O[V.filePath]??!1?J(V.filePath):W(V.filePath,V.lastModified),T(null)},onEdit:()=>{y(V)},onDelete:()=>{v(V),T(null)},onClose:()=>T(null)})})(),C&&n(ik,{onClose:()=>S(!1),onCreateNew:()=>{S(!1),x(!0)}}),b&&n(lk,{rule:b,onConfirm:E,onCancel:()=>v(null)})]})}):n(ok,{})}),yk=Object.freeze(Object.defineProperty({__proto__:null,default:gk,loader:fk,meta:mk},Symbol.toStringTag,{value:"Module"}));function Na(e){return`${e.filePath||""}::${e.name}`}function Bp(e,t){const r=Ke(),{showToast:s}=ai(),[o,a]=P(new Map);se(()=>{if(r.state==="idle"&&r.data){const m=r.data;m!=null&&m.error&&s(`Error: ${m.error}`,"error",6e3)}},[r.state,r.data,s]),se(()=>{var f;if(o.size===0)return;const m=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{o.forEach((b,v)=>{b===x&&m.add(v)})})}),e==null||e.forEach(y=>{o.forEach((g,x)=>{g===y&&m.add(x)})}),m.size>0&&a(y=>{const g=new Map(y);return m.forEach(x=>g.delete(x)),g})},[t,e,o]);const i=ce(m=>{console.log("Generate analysis clicked for entity:",m.sha,m.name);const f=Na(m);a(g=>new Map(g).set(f,m.sha));const y=new FormData;y.append("entitySha",m.sha),y.append("filePath",m.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=ce(m=>{const f=m.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),a(x=>{const b=new Map(x);return f.forEach(v=>b.set(Na(v),v.sha)),b});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),c=ce(m=>(e==null?void 0:e.includes(m))??!1,[e]),u=ce(m=>{const f=Na(m);return o.has(f)},[o]),p=ce(m=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(m)}))??!1},[t]),h=pe(()=>Array.from(o.keys()),[o]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:u,isEntityInQueue:p,pendingEntityKeys:h}}function Qi({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:o=!1,analyzeAllText:a="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:d("div",{className:"flex justify-between items-center px-3 py-2",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),d("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"})}),d("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),d("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:s&&n("button",{onClick:s,disabled:o,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:o?a:"Analyze all entities",children:a})})]})]})]})})}function xk({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"}},s={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 a=s[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:a.textColor},children:a.label})})}const o=r[e]||{label:"?",bgColor:"bg-gray-500"};return d("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${o.bgColor}`,title:e,children:o.label}),o.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Zi({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:o,entityCount:a,state:i,lastModified:l,actionButton:c,uncommittedCount:u,children:p,isNotAnalyzable:h=!1,isUncommitted:m=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[d("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(Id,{filePath:e}),s&&n(xk,{status:typeof s=="string"?s:s.status,variant:"full"}),m&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(m||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:o}),d("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:d("span",{className:"text-[13px] text-[#3e3e3e]",children:[a," ",a===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:jp(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:c})]})]})]}),t&&p&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:p})]})}function Xi({entities:e,maxPreviews:t=3}){var s,o,a,i,l;const r=[];for(const c of e){if(r.length>=t)break;const u=((o=(s=c.analyses)==null?void 0:s[0])==null?void 0:o.scenarios)||[];if(c.entityType==="library"){const p=u.find(h=>{var m,f;return((m=h.metadata)==null?void 0:m.executionResult)||((f=h.metadata)==null?void 0:f.error)});p&&r.push({type:"library",scenario:p,entitySha:c.sha})}else if(c.entityType==="visual"){const p=u.find(h=>{var m,f;return(f=(m=h.metadata)==null?void 0:m.screenshotPaths)==null?void 0:f[0]});if(p){const h=(i=(a=p.metadata)==null?void 0:a.screenshotPaths)==null?void 0:i[0],m=!!((l=p.metadata)!=null&&l.error);h&&r.push({type:"screenshot",screenshot:h,hasError:m,scenario:p,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ve,{children:r.map((c,u)=>{if(c.type==="screenshot"&&c.screenshot){const p=c.hasError?"border-red-400":"border-gray-200";return d(ke,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.entitySha}`,className:`relative w-[50px] h-[38px] border ${p} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(ut,{screenshotPath:c.screenshot,alt:`Preview ${u+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.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(Ws,{size:12,color:"white"})})]},`screenshot-${u}`)}return c.type==="library"&&c.scenario&&c.entitySha?n(Ep,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${u}`):null})})}function el({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var p,h;const o=t||r?[{entityShas:[e.sha]}]:[],a=_t(e,o,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(a==="not-analyzed"||a==="out-of-date")&&!t&&!r,u=(((h=(p=e.analyses)==null?void 0:p[0])==null?void 0:h.scenarios)||[]).filter(m=>{var f,y;return(y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return d("div",{className:"bg-white rounded-lg",children:[d(ke,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[d("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(St,{type:"type"})})}):n(St,{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(Ui,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("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?a==="queued"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("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"]}):a==="analyzing"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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..."]}):a==="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"}):a==="out-of-date"?n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(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:m=>{m.preventDefault(),m.stopPropagation(),s(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"})})]})]})]}),u.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:u.map((m,f)=>{var g,x;const y=(x=(g=m.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(ke,{to:`/entity/${e.sha}?scenario=${m.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(ut,{screenshotPath:y,alt:m.name,className:"max-w-full max-h-full object-contain object-center"})},m.id):null})})]})}function bk({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:o,entityType:a,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:u,onGenerateAllSimulations:p,totalFilesCount:h,totalEntitiesCount:m,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,b]=lr(),[v,N]=P(new Set),[w,C]=P(""),[S,k]=P(!1),[T,_]=P("all"),[$,M]=P("desc"),R=a||"all",z=pe(()=>{let E=e;return R!=="all"&&(E=E.filter(F=>F.entityType===R)),o==="analyzed"&&(E=E.filter(F=>F.analyses&&F.analyses.length>0)),E},[e,R,o]),O=pe(()=>{const E=new Map,F=new Map,I=new Map;z.forEach(Y=>{var ne,oe;const B=`${Y.filePath}::${Y.name}`,H=F.get(B);if(!H)F.set(B,Y),I.set(B,[]);else{const Z=((ne=H.metadata)==null?void 0:ne.editedAt)||H.createdAt||"",re=((oe=Y.metadata)==null?void 0:oe.editedAt)||Y.createdAt||"";let ue=!1;if(re>Z)ue=!0;else if(re===Z){const we=H.createdAt||"";ue=(Y.createdAt||"")>we}ue?(I.get(B).push(H),F.set(B,Y)):I.get(B).push(Y)}}),F.forEach((Y,B)=>{var ne;if(!(Y.analyses&&Y.analyses.length>0)&&((ne=Y.metadata)!=null&&ne.previousVersionWithAnalyses)){const Z=(I.get(B)||[]).find(re=>{var ue;return re.sha===((ue=Y.metadata)==null?void 0:ue.previousVersionWithAnalyses)});Z&&Z.analyses&&Z.analyses.length>0&&(Y.analyses=Z.analyses)}}),Array.from(F.values()).sort((Y,B)=>{var oe,Z,re,ue;const H=!((oe=Y.metadata)!=null&&oe.notExported)&&!((Z=Y.metadata)!=null&&Z.namedExport),ne=!((re=B.metadata)!=null&&re.notExported)&&!((ue=B.metadata)!=null&&ue.namedExport);return H&&!ne?-1:!H&&ne?1:0}).forEach(Y=>{var Z,re,ue,we,je;const B=Y.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 H=E.get(B);H.entities.push(Y),H.totalCount++,(Z=Y.metadata)!=null&&Z.isUncommitted&&H.uncommittedCount++;const ne=((we=(ue=(re=Y.analyses)==null?void 0:re[0])==null?void 0:ue.scenarios)==null?void 0:we.length)||0;H.simulationCount+=ne;const oe=((je=Y.metadata)==null?void 0:je.editedAt)||Y.updatedAt;oe&&(!H.lastUpdated||new Date(oe)>new Date(H.lastUpdated))&&(H.lastUpdated=oe)});const K=(i==null?void 0:i.jobs)||[],Q=Y=>{const B=`${Y.filePath||""}::${Y.name}`;return(c==null?void 0:c.includes(B))||!1};E.forEach(Y=>{const B=Y.entities.map(H=>Q(H)?"queued":_t(H,K));B.includes("analyzing")||B.includes("queued")?Y.state="analyzing":B.includes("incomplete")?Y.state="incomplete":B.includes("out-of-date")?Y.state="out-of-date":B.includes("not-analyzed")?Y.state="not-analyzed":Y.state="up-to-date"}),E.forEach(Y=>{var B,H,ne,oe,Z;for(const re of Y.entities){if(Y.previewScreenshots.length+Y.previewLibraryScenarios.length>=3)break;const we=((H=(B=re.analyses)==null?void 0:B[0])==null?void 0:H.scenarios)||[];if(re.entityType==="library"){const je=we.find(be=>{var Ee,X;return((Ee=be.metadata)==null?void 0:Ee.executionResult)||((X=be.metadata)==null?void 0:X.error)});je&&Y.previewLibraryScenarios.push({scenario:je,entitySha:re.sha})}else{const je=we.find(be=>{var Ee,X;return(X=(Ee=be.metadata)==null?void 0:Ee.screenshotPaths)==null?void 0:X[0]});if(je){const be=(oe=(ne=je.metadata)==null?void 0:ne.screenshotPaths)==null?void 0:oe[0],Ee=!!((Z=je.metadata)!=null&&Z.error);be&&!Y.previewScreenshots.includes(be)&&(Y.previewScreenshots.push(be),Y.previewScreenshotErrors.push(Ee))}}}});const V=Array.from(E.values());return V.sort((Y,B)=>{if(o==="analyzed"){const oe=Math.max(...Y.entities.filter(re=>{var ue,we;return(we=(ue=re.analyses)==null?void 0:ue[0])==null?void 0:we.createdAt}).map(re=>new Date(re.analyses[0].createdAt).getTime()),0),Z=Math.max(...B.entities.filter(re=>{var ue,we;return(we=(ue=re.analyses)==null?void 0:ue[0])==null?void 0:we.createdAt}).map(re=>new Date(re.analyses[0].createdAt).getTime()),0);return $==="desc"?Z-oe:oe-Z}if(Y.uncommittedCount>0&&B.uncommittedCount===0)return-1;if(Y.uncommittedCount===0&&B.uncommittedCount>0)return 1;const H=Y.lastUpdated?new Date(Y.lastUpdated).getTime():0,ne=B.lastUpdated?new Date(B.lastUpdated).getTime():0;return $==="desc"?ne-H:H-ne}),V},[z,o,$,i,c]),U=pe(()=>{let E=O;if(T!=="all"&&(E=E.filter(F=>F.state===T)),w.trim()){const F=w.toLowerCase();E=E.filter(I=>I.filePath.toLowerCase().includes(F))}return E},[O,w,T]),W=(t-1)*r,J=W+r,j=U.slice(W,J),D=Math.ceil(U.length/r),A=E=>{N(F=>{const I=new Set(F);return I.has(E)?I.delete(E):I.add(E),I})},L=()=>{M(E=>E==="desc"?"asc":"desc")};return d("div",{children:[d("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"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative w-[130px]",children:[d("select",{value:R,onChange:E=>{const F=E.target.value,I=new URLSearchParams(x);F==="all"?I.delete("entityType"):I.set("entityType",F),I.set("page","1"),b(I)},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(At,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"relative w-[130px]",children:[d("select",{value:T,onChange:E=>_(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(At,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Kr,{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:w,onChange:E=>C(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"})]})]})]}),h!==void 0&&m!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("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?"file":"files"]}),d("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:d("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:"|"}),d("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((E,F)=>E+F.totalCount,0)})," ",U.reduce((E,F)=>E+F.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?d("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[U.filter(E=>E.uncommittedCount>0).length," ","uncommitted"," ",U.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"})})]}):d("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),j.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{N(new Set(j.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(Ad,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{N(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(Td,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Qi,{showActions:!0,sortOrder:$,onSortChange:L}),n("div",{className:"flex flex-col gap-[3px]",children:j.map(E=>{const F=v.has(E.filePath),K=E.entities.filter(B=>(B.entityType==="visual"||B.entityType==="library")&&(_t(B,(i==null?void 0:i.jobs)||[])==="not-analyzed"||_t(B,(i==null?void 0:i.jobs)||[])==="out-of-date"||_t(B,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,Q=B=>{var H;return((H=s==null?void 0:s.currentEntityShas)==null?void 0:H.includes(B))||!1},V=B=>{var H;return l!=null&&l(B)?!0:((H=i==null?void 0:i.jobs)==null?void 0:H.some(ne=>{var oe;return(oe=ne.entityShas)==null?void 0:oe.includes(B.sha)}))||!1},Y=B=>{u==null||u(B)};return n(Zi,{filePath:E.filePath,isExpanded:F,onToggle:()=>A(E.filePath),simulationPreviews:n(Xi,{entities:E.entities,maxPreviews:1}),entityCount:E.totalCount,state:E.state,lastModified:E.lastUpdated,uncommittedCount:E.uncommittedCount,isUncommitted:E.uncommittedCount>0,actionButton:K?n("button",{onClick:B=>{B.stopPropagation();const H=E.entities.filter(ne=>(ne.entityType==="visual"||ne.entityType==="library")&&(_t(ne,(i==null?void 0:i.jobs)||[])==="not-analyzed"||_t(ne,(i==null?void 0:i.jobs)||[])==="out-of-date"||_t(ne,(i==null?void 0:i.jobs)||[])==="incomplete"));p==null||p(H)},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,H)=>{var ue,we,je,be;const ne=!((ue=B.metadata)!=null&&ue.notExported)&&!((we=B.metadata)!=null&&we.namedExport),oe=!((je=H.metadata)!=null&&je.notExported)&&!((be=H.metadata)!=null&&be.namedExport);if(ne&&!oe)return-1;if(!ne&&oe)return 1;const Z=B.entityType==="visual"||B.entityType==="library",re=H.entityType==="visual"||H.entityType==="library";return Z&&!re?-1:!Z&&re?1:B.name.localeCompare(H.name)}).map(B=>n(el,{entity:B,isActivelyAnalyzing:Q(B.sha),isQueued:V(B),onGenerateSimulation:Y},B.sha))},E.filePath)})}),D>1&&d("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"}),d("span",{children:["Page ",t," of ",D]}),t<D&&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 vk=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function wk({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),o=r.searchParams.get("filter")||null,a=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[c,u]=await Promise.all([zn(),hr()]);return le({entities:c,currentCommit:u,page:s,filter:o,entityType:a,queueState:l})}catch(r){return console.error("Failed to load entities:",r),le({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Nk=nt(function(){var w,C,S;const{entities:t,currentCommit:r,page:s,filter:o,entityType:a,queueState:i,error:l}=lt();Bt();const[c,u]=lr(),[p,h]=P(!1);Yt({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Bp((C=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:C.currentEntityShas,i),x=t||[],b=pe(()=>{const k=new Set([]);for(const T of x)k.add(T.filePath??"No File Path");return Array.from(k)},[x]),v=pe(()=>{let k=x;return p&&(k=k.filter(T=>{var _;return(_=T.metadata)==null?void 0:_.isUncommitted})),k.sort((T,_)=>{var $,M,R,z,O,U;return($=T.metadata)!=null&&$.isUncommitted&&!((M=_.metadata)!=null&&M.isUncommitted)?-1:!((R=T.metadata)!=null&&R.isUncommitted)&&((z=_.metadata)!=null&&z.isUncommitted)?1:new Date(((O=_.metadata)==null?void 0:O.editedAt)||0).getTime()-new Date(((U=T.metadata)==null?void 0:U.editedAt)||0).getTime()})},[x,p]),N=pe(()=>{var T;const k=new Set([]);for(const _ of x)(T=_.metadata)!=null&&T.isUncommitted&&k.add(_.filePath??"No File Path");return Array.from(k)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("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:d("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("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(bk,{entities:v,page:s,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:o,entityType:a,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:p,onToggleUncommitted:()=>h(!p)})]})})}),Sk=Object.freeze(Object.defineProperty({__proto__:null,default:Nk,loader:wk,meta:vk},Symbol.toStringTag,{value:"Module"})),Ck=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function kk({request:e}){var t;try{const r=await Ye();if(!r)return le({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await De(r),o=Ce()||process.cwd(),a=gp(o)||"";let i="";try{const c=await go();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const u=c.webapps.map(p=>p.framework).filter(Boolean);u.length>0&&(i=u.join(", "))}}catch{}const l=kp(r);return le({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:a,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),le({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Ek({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return le({success:!1,error:"Missing feature name"},{status:400});const o=await Ye();return o?(r==="clearAccess"?await or({projectSlug:o,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await or({projectSlug:o,metadataUpdate:{labs:{[r]:s}}}),le({success:!0,error:null})):le({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),le({success:!1,error:"Failed to save labs configuration"},{status:500})}}const _k=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],Zc="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",jk=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function Pk({onClose:e}){const t=ye(null),r=ye(0);return se(()=>{const s=t.current;if(!s)return;const o=100,a=2e3,i=500;let l=null,c=!1;const u=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const p=Date.now()-r.current,h=s.scrollTop>o,m=p>a;h&&m&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",u,{passive:!0}),()=>{s.removeEventListener("scroll",u),l&&clearInterval(l)}},[]),d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Zc}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:d("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),d("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Zc,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Ak({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const o=(i=s.data)==null?void 0:i.error,a=(l=s.data)==null?void 0:l.success;return d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:c=>{c.target===c.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),d(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:c=>r(c.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),o&&n("p",{className:"text-red-600 text-sm mt-2",children:o}),a&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const Tk=nt(function(){const{labs:t,unlockCode:r,error:s}=lt(),o=Ke(),a=Ke(),i=Ke(),[l,c]=P(""),[u,p]=P(!1),[h,m]=P(!1);Yt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:d("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:s})})]})}):f?d("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:_k.map(y=>{var b;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=a.state==="submitting"&&((b=a.formData)==null?void 0:b.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:d("div",{className:"flex items-center justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),d(a.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:d("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),d("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),d(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):d("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[u&&n(Pk,{onClose:()=>p(!1)}),h&&n(Ak,{onClose:()=>m(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:o}),d("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>m(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),d("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),d("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:jk.map(y=>d("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[d("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",d("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:d("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),Mk=Object.freeze(Object.defineProperty({__proto__:null,action:Ek,default:Tk,loader:kk,meta:Ck},Symbol.toStringTag,{value:"Module"}));function $k(e,t,r){const[s,o]=P(()=>new Set),[a,i]=P(()=>new Set),l=ye([]),c=ye([]);return se(()=>{(t.length!==l.current.length||t.some((g,x)=>g!==l.current[x]))&&(l.current=t,o(g=>{const x=new Set;return t.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[t]),se(()=>{(r.length!==c.current.length||r.some((g,x)=>g!==c.current[x]))&&(c.current=r,i(g=>{const x=new Set;return r.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:a,setExpandedUncommitted:o,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(b=>{const v=new Set(b);return v.has(y)?v.delete(y):v.add(y),v})},expandAllUncommitted:()=>{o(new Set(t))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Fk(e,t,r){const[s,o]=P(null),[a,i]=P(null),l=Ke();se(()=>{var h,m;((h=l.data)==null?void 0:h.oldContent)!==void 0&&((m=l.data)==null?void 0:m.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=h=>{o({type:"file",path:h}),i(null);const m=new FormData;m.append("actionType","getDiff"),m.append("filePath",h),m.append("diffType","branch"),m.append("baseBranch",e),m.append("currentBranch",t||""),l.submit(m,{method:"post"})},u=(h,m)=>{o({type:"entity",path:h,entitySha:m}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",m),l.submit(f,{method:"post"})},p=()=>{o(null),i(null)};return{diffView:s,diffContent:a,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:u,handleCloseDiff:p}}function Rk({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:o}){var u;const[a,i]=P(!1),[l,c]=P(!1);return se(()=>{c(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:d("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[d("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[d("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&&d("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((u=s.find(p=>p.sha===e.entitySha))==null?void 0:u.name)||e.entitySha]})]}),d("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!a),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:a?"Show changes only":"Show full file",children:a?"Show Changes Only":"Show Full File"}),n("button",{onClick:o,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Um,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!a,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:o,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function Dk({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:o,expandedFiles:a,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:u,onBranchChange:p,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:w}])=>{const C=w.filter(S=>i(S.sha)||l(S)).map(S=>S.sha);return C.length>0?[{entityShas:C}]:[]}),b=N=>{const w=N.map(C=>_t(C,x));return w.includes("analyzing")||w.includes("queued")?"analyzing":w.includes("out-of-date")?"out-of-date":w.includes("not-analyzed")?"not-analyzed":"up-to-date"},v=pe(()=>[...e].sort((N,w)=>{const C=N[1].entities.reduce((_,$)=>{var R;const M=((R=$.metadata)==null?void 0:R.editedAt)||$.updatedAt;return M?_?new Date(M)>new Date(_)?M:_:M:_},null),S=w[1].entities.reduce((_,$)=>{var R;const M=((R=$.metadata)==null?void 0:R.editedAt)||$.updatedAt;return M?_?new Date(M)>new Date(_)?M:_:M:_},null);if(!C&&!S)return 0;if(!C)return 1;if(!S)return-1;const k=new Date(C).getTime(),T=new Date(S).getTime();return c==="desc"?T-k:k-T}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(Qi,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,entities:C,isUncommitted:S}])=>{const k=a.has(N),T=b(C),_=C.reduce((z,O)=>{var W;const U=((W=O.metadata)==null?void 0:W.editedAt)||O.updatedAt;return U?z?new Date(U)>new Date(z)?U:z:U:z},null),M=C.filter(z=>z.entityType==="visual"||z.entityType==="library").length===0;let R;return M?R=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):T==="analyzing"?R=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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..."]}):T==="up-to-date"?R=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"}):T==="out-of-date"?R=n("button",{onClick:z=>{z.stopPropagation(),C.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&!i(O.sha)&&!l(O)).forEach(O=>h(O))},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"}):T==="not-analyzed"&&(R=n("button",{onClick:z=>{z.stopPropagation(),C.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&!i(O.sha)&&!l(O)).forEach(O=>h(O))},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(Zi,{filePath:N,isExpanded:k,onToggle:()=>u(N),fileStatus:w,isUncommitted:S,simulationPreviews:n(Xi,{entities:C,maxPreviews:1}),entityCount:C.length,state:T,lastModified:_,isNotAnalyzable:M,actionButton:R,children:C.sort((z,O)=>{const U=z.entityType==="visual"||z.entityType==="library",W=O.entityType==="visual"||O.entityType==="library";return U&&!W?-1:!U&&W?1:0}).map(z=>n(el,{entity:z,isActivelyAnalyzing:i(z.sha),isQueued:l(z),onGenerateSimulation:h},z.sha))},N)})})]}):d("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 Ik({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:o,projectSlug:a,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:u,onShowFileDiff:p,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=pe(()=>{const N=[];return e.forEach(([w,{editedEntities:C}])=>{const S=C.filter(k=>s(k.sha)||o(k)).map(k=>k.sha);S.length>0&&N.push({entityShas:S})}),N},[e,s,o]),b=pe(()=>{const N=new Map;return e.forEach(([w,{editedEntities:C}])=>{const S=C.map($=>_t($,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 T=C.reduce(($,M)=>{var z;const R=((z=M.metadata)==null?void 0:z.editedAt)||M.updatedAt;return R&&(!$||new Date(R)>new Date($))?R:$},null),_=C.filter($=>$.entityType==="visual"||$.entityType==="library").length;N.set(w,{state:k,lastModified:T,analyzableCount:_})}),N},[e,x]),v=pe(()=>[...e].sort((N,w)=>{const C=b.get(N[0]),S=b.get(w[0]),k=C==null?void 0:C.lastModified,T=S==null?void 0:S.lastModified;if(!k&&!T)return 0;if(!k)return 1;if(!T)return-1;const _=new Date(k).getTime(),$=new Date(T).getTime();return c==="desc"?$-_:_-$}),[e,b,c]);return e.length===0?d("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."})]}):d("div",{children:[n(Qi,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,editedEntities:C}])=>{const S=r.has(N),k=b.get(N),{state:T,lastModified:_,analyzableCount:$}=k,M=$===0;let R;return M?R=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):T==="analyzing"?R=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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..."]}):T==="up-to-date"?R=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"}):T==="out-of-date"?R=n("button",{onClick:z=>{z.stopPropagation(),C.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&!s(O.sha)&&!o(O)).forEach(O=>h(O))},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"}):T==="not-analyzed"&&(R=n("button",{onClick:z=>{z.stopPropagation(),C.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&!s(O.sha)&&!o(O)).forEach(O=>h(O))},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(Zi,{filePath:N,isExpanded:S,onToggle:()=>u(N),fileStatus:w,simulationPreviews:n(Xi,{entities:C,maxPreviews:1}),entityCount:C.length,state:T,lastModified:_,isNotAnalyzable:M,isUncommitted:!0,actionButton:R,children:C.sort((z,O)=>{const U=z.entityType==="visual"||z.entityType==="library",W=O.entityType==="visual"||O.entityType==="library";return U&&!W?-1:!U&&W?1:0}).map(z=>n(el,{entity:z,isActivelyAnalyzing:s(z.sha),isQueued:o(z),onGenerateSimulation:h},z.sha))},N)})})]})}function Ok({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:d("nav",{className:"flex gap-8 items-center",children:[d("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:[d("span",{className:"flex items-center gap-2",children:["Branch Changes",s>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:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),d("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:[d("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 Lk=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function zk({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),o=t.get("diffType"),a=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let c;return o==="branch"?c=Os(s,a,i):c=fb(s),le({...c,entitySha:l})}return le({error:"Unknown action"},{status:400})}async function Bk({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),o=r.searchParams.get("viewBranch"),a=t.analysisQueue,i=a?a.getState():{paused:!1,jobs:[]},[l,c,u]=await Promise.all([zn(),hr(),Ye()]),p=gr(),h=ub(),m=pb(),f=hb(),y=o||h,g=s||m;let x=[];return y&&y!==g&&(x=Hu(g,y)),le({entities:l||[],gitStatus:p,currentBranch:y,actualCurrentBranch:h,defaultBranch:m,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:c,projectSlug:u,queueState:i})}catch(r){return console.error("Failed to load git data:",r),le({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 Yk=nt(function(){var he,Te;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:o,defaultBranch:a,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:u,projectSlug:p,queueState:h}=lt();Yt({source:"git-page"});const[m,f]=lr(),[y,g]=P(null),[x,b]=P("desc"),[v,N]=P("branch"),w=m.get("expanded")==="true",C=()=>{b(xe=>xe==="desc"?"asc":"desc")},S=Ke(),k=S.data;se(()=>{s&&l&&s!==l&&S.state==="idle"&&!k&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,S,k]);const T=pe(()=>{const xe=Dp(r,t);return Array.from(xe.entries()).sort((Oe,Je)=>Oe[0].localeCompare(Je[0]))},[r,t]),_=pe(()=>{const xe=L2(c,t,k);return Array.from(xe.entries()).sort((Oe,Je)=>Oe[0].localeCompare(Je[0]))},[c,t,k]),$=pe(()=>z2(r,t),[r,t]),M=pe(()=>v==="uncommitted"?T:_,[v,T,_]),R=pe(()=>M.map(([xe])=>xe),[M]),{expandedUncommitted:z,setExpandedUncommitted:O,toggleFile:U,expandAllUncommitted:W,collapseAllUncommitted:J}=$k(w,R,[]),{diffView:j,diffContent:D,isLoading:A,handleShowFileDiff:L,handleCloseDiff:E}=Fk(l,s),F=(he=u==null?void 0:u.metadata)==null?void 0:he.currentRun,I=new Set((F==null?void 0:F.currentEntityShas)||[]),K=new Set(h.jobs.flatMap(xe=>xe.entityShas||[])),Q=new Set(((Te=h.currentlyExecuting)==null?void 0:Te.entityShas)||[]),{isAnalyzing:V,handleGenerateSimulation:Y,handleGenerateAllSimulations:B,isEntityBeingAnalyzed:H,isEntityPending:ne}=Bp(F==null?void 0:F.currentEntityShas,h),oe=xe=>ne(xe)||K.has(xe.sha)||Q.has(xe.sha),Z=xe=>{xe===(o||s)?m.delete("viewBranch"):m.set("viewBranch",xe),f(m)},re=xe=>{xe===a?m.delete("compare"):m.set("compare",xe),f(m)},ue=()=>{const Oe=M.flatMap(([Je,bt])=>bt.editedEntities||bt.entities||[]).filter(Je=>!I.has(Je.sha)&&!K.has(Je.sha)&&!Q.has(Je.sha)&&!ne(Je));B(Oe)},we=T.length,je=_.length,be=M.flatMap(([xe,Oe])=>Oe.editedEntities||Oe.entities||[]),Ee=be.filter(xe=>xe.entityType==="visual"||xe.entityType==="library"),X=Ee.length>0&&Ee.every(xe=>I.has(xe.sha)),fe=Ee.length>0&&!X&&Ee.every(xe=>K.has(xe.sha)||Q.has(xe.sha)),ae=V||X||fe,ie=X?"Analyzing...":fe?"Queued...":V?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),d("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(Ok,{activeTab:v,onTabChange:N,uncommittedCount:we,branchCount:je})}),s&&v==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===a?d("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:a}),"."]}):d("div",{className:"flex gap-6 items-center",children:[d("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?d("div",{className:"relative w-50",children:[n("select",{value:s,onChange:xe=>Z(xe.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(xe=>n("option",{value:xe,children:xe},xe))}),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:s})]}),d("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),d("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:xe=>re(xe.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(xe=>xe!==s).map(xe=>n("option",{value:xe,children:xe},xe))}),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:d("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:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:M.length})," ","modified ",M.length===1?"file":"files"]}),d("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:d("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:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:be.length})," ",be.length===1?"entity":"entities"]})]}),M.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:W,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(Ad,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("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(Td,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[v==="branch"&&s&&n(Dk,{files:_,currentBranch:s,defaultBranch:a,baseBranch:l,allBranches:i,expandedFiles:z,isEntityBeingAnalyzed:H,isEntityQueued:oe,sortOrder:x,onToggleFile:xe=>U(xe,z,O),onBranchChange:re,onGenerateSimulation:Y,onSortChange:C,onAnalyzeAll:ue,analyzeAllDisabled:ae,analyzeAllText:ie}),v==="uncommitted"&&n(Ik,{files:T,entityImpactMap:$,expandedFiles:z,isEntityBeingAnalyzed:H,isEntityQueued:oe,projectSlug:p,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:xe=>U(xe,z,O),onShowFileDiff:L,onGenerateSimulation:Y,onSortChange:C,onAnalyzeAll:ue,analyzeAllDisabled:ae,analyzeAllText:ie})]}),j&&n(Rk,{diffView:j,diffContent:D,isLoading:A,entities:t,onClose:E}),y&&p&&n(hn,{projectSlug:p,onClose:()=>g(null)})]})})}),Uk=Object.freeze(Object.defineProperty({__proto__:null,action:zk,default:Yk,loader:Bk,meta:Lk},Symbol.toStringTag,{value:"Module"}));function Ys(e){const t=e.name.toLowerCase();if(e.name==="Desktop"||e.name==="Full HD"||e.name==="HD")return"desktop";if(e.name==="Laptop"||e.name==="Small Laptop")return"laptop";if(e.name==="Tablet")return"tablet";if(e.name==="Mobile"||t.includes("iphone")||t.includes("pixel")||t.includes("galaxy")||t.includes("phone"))return"mobile";if(t.includes("ipad")||t.includes("tablet"))return"tablet";if(t.includes("laptop"))return"laptop";if(t.includes("desktop"))return"desktop";const r=e.height>e.width;return r&&e.width>=700?"tablet":r?"mobile":e.width>1200?"desktop":"laptop"}const Wk=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],Jk=[{name:"iPhone 16",width:393,height:852},{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone SE",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"iPad mini",width:744,height:1133}],Yp=[{category:"Desktop",presets:[{name:"Full HD",width:1920,height:1080},{name:"Desktop",width:1440,height:900},{name:"HD",width:1280,height:720}]},{category:"Laptop",presets:[{name:"Laptop",width:1366,height:768},{name:"Small Laptop",width:1024,height:768}]},{category:"Tablet",presets:[{name:'iPad Pro 12.9"',width:1024,height:1366},{name:"iPad Air",width:820,height:1180},{name:"Tablet",width:768,height:1024},{name:"iPad mini",width:744,height:1133}]},{category:"Mobile",presets:[{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone 16",width:393,height:852},{name:"iPhone 14",width:390,height:844},{name:"Mobile",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"Galaxy S",width:360,height:800}]}];function Up(e,t){if(e&&Object.keys(e).length>0&&Object.values(e).some(l=>"default"in l))return Object.entries(e).map(([l,c])=>({name:l,width:c.width,height:c.height}));const r=(t==null?void 0:t.includes("mobile-app"))??!1,s=r?Jk:Wk,o=s.map(l=>{const c=e==null?void 0:e[l.name];return c?{...l,width:c.width,height:c.height}:l});if(!e||r)return o;const a=new Set(s.map(l=>l.name)),i=Object.entries(e).filter(([l])=>!a.has(l)).map(([l,c])=>({name:l,width:c.width,height:c.height}));return[...o,...i]}const $s={width:24,height:76};function Hk({width:e,height:t,enabled:r=!0,children:s}){if(!r)return n(ve,{children:s});const o=12,a=48,i=28,l=e+o*2,c=t+a+i;return d("div",{style:{width:`${l}px`,height:`${c}px`,background:"#1a1a1a",borderRadius:"44px",padding:`${a}px ${o}px ${i}px`,position:"relative",boxShadow:"0 0 0 1px rgba(255,255,255,0.08), 0 8px 32px rgba(0,0,0,0.4)"},children:[n("div",{style:{position:"absolute",top:"14px",left:"50%",transform:"translateX(-50%)",width:"100px",height:"24px",background:"#000",borderRadius:"12px"}}),n("div",{style:{width:`${e}px`,height:`${t}px`,borderRadius:"6px",overflow:"hidden",position:"relative"},children:s}),n("div",{style:{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%)",width:"120px",height:"4px",background:"rgba(255,255,255,0.25)",borderRadius:"2px"}})]})}function Fs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Vk({from:e,to:t,lastStep:r,lastStepLabel:s,handoffSummary:o,featureName:a,onContinue:i,onStartFresh:l}){const c=ce(u=>{u.key==="Enter"&&(u.preventDefault(),i())},[i]);return se(()=>(window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)),[c]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[d("div",{className:"flex items-center gap-2 mb-3",children:[n("div",{className:"w-2 h-2 rounded-full bg-amber-400"}),n("h2",{className:"text-lg font-semibold text-white",children:"Provider Changed"})]}),d("p",{className:"text-sm text-amber-300 mb-4",children:[Fs(e)," → ",Fs(t)]}),d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-4 text-sm space-y-1",children:[a&&d("div",{children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:a})]}),r!=null&&s&&d("div",{children:[n("span",{className:"text-[#999]",children:"Last step:"})," ",d("span",{className:"text-white",children:[r," of 18 — ",s]})]})]}),o&&d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-4 text-sm",children:[n("div",{className:"text-[#999] mb-1",children:"Previous provider's notes:"}),n("div",{className:"text-[#ccc] italic",children:o})]}),d("p",{className:"text-xs text-[#999] mb-4",children:["Continuing will generate a handoff context with uncommitted changes and progress history for ",Fs(t)," to review."]}),d("button",{onClick:i,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-amber-600 text-white font-medium hover:bg-amber-700 ring-2 ring-amber-400/50",children:["Continue with ",Fs(t)]}),n("button",{onClick:l,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Start Fresh"})]})})}function Kk({featureName:e,editorStep:t,editorStepLabel:r,onContinue:s,onStartFresh:o}){const a=ce(i=>{i.key==="Enter"&&(i.preventDefault(),s())},[s]);return se(()=>(window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)),[a]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Resume Previous Session?"}),n("p",{className:"text-sm text-[#999] mb-4",children:"An editor session is still in progress:"}),d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-5 text-sm",children:[e&&d("div",{className:"mb-1",children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:e})]}),t!=null&&r&&d("div",{children:[n("span",{className:"text-[#999]",children:"Step:"})," ",d("span",{className:"text-white",children:[t," (",r,")"]})]})]}),n("button",{onClick:s,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Continue Session"}),o&&n("button",{onClick:o,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Start Fresh"})]})})}function Gk({onStartNextFeature:e,onContinueInSession:t}){const r=ce(s=>{s.key==="Enter"&&(s.preventDefault(),e())},[e]);return se(()=>(window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)),[r]),n("div",{className:"absolute inset-0 flex items-center justify-center bg-[#1e1e1e]/90 z-10",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Feature Complete!"}),n("p",{className:"text-sm text-[#999] mb-5",children:"Your feature has been pushed. What would you like to do next?"}),n("button",{onClick:e,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Start Next Feature"}),n("button",{onClick:t,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Continue in Current Session"}),n("p",{className:"text-xs text-[#666] mt-3 text-center",children:"Press Enter to start a new feature with a fresh context"})]})})}const qk={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"},Qk={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Prepare the project environment and dependencies for prototyping.",3:"Build a working prototype quickly to validate the concept.",4:"Verify the prototype works correctly and fix any issues.",5:"Confirm the prototype looks right and get user approval to proceed.",6:"Read the code and plan all component and function extractions.",7:"Extract components and functions via TDD — components first, then functions.",8:"Record all extracted functions and components in the glossary.",9:"Analyze imports and verify all components are captured correctly.",10:"Create app-level scenarios that show full pages with realistic data.",11:"Create user-persona scenarios that exercise the app from different perspectives.",12:"Review all screenshots and check for visual errors or regressions.",13:"Create or update the journal entry documenting what was built.",14:"Final review of screenshots, audit for completeness.",15:"Present a summary of all work to the user for approval.",16:"Commit all changes to git.",17:"Update the journal with final details and amend the commit.",18:"Push the branch to the remote repository."},Zk={1:"Survey",2:"App Scenarios",3:"Component Scenarios",4:"Preview",5:"Discuss",6:"Decompose",7:"Extract",8:"Recapture",9:"Journal",10:"Present"},Xk={1:"Survey the existing codebase to understand pages, components, and dependencies.",2:"Create app-level scenarios showing full pages with realistic data.",3:"Create component-level scenarios for isolated component previews.",4:"Preview all captured scenarios and verify they look correct.",5:"Discuss the migration plan and prioritize which pages to decompose.",6:"Plan the decomposition of pages into clean, reusable components.",7:"Extract components and functions with tests via TDD.",8:"Recapture scenarios after extraction to verify nothing broke.",9:"Document the migration progress in a journal entry.",10:"Present the migration results for review and approval."},e5=18,t5=10;function n5({projectTitle:e,featureName:t,editorStep:r,editorStepLabel:s,migrationMode:o}){const[a,i]=P(!1),[l,c]=P(null),u=ye(null);se(()=>{if(!a)return;const b=v=>{u.current&&!u.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[a]);const p=t&&r!=null,h=o==="active",m=h?Zk:qk,f=h?Xk:Qk,y=h?t5:e5,g=p?s||m[r]||"?":null;return d("div",{className:"h-8 shrink-0 flex items-center justify-between px-3 bg-[#2a2a2a] border-b border-[#333] text-xs select-none",children:[d("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("span",{className:"text-[#888] truncate",children:e||"New Project"}),n("span",{className:"text-[#555]",children:">"}),n("span",{className:"text-[#ccc] font-medium truncate",children:t||"New Working Session"})]}),p&&d("div",{className:"relative",ref:u,children:[d("button",{onClick:()=>i(b=>!b),className:"flex items-center gap-1.5 text-[#ccc] hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"text-[#555]",children:"::"}),d("span",{children:["Step ",r,d("span",{className:"text-[#888]",children:[" / ",y]}),":"," ",g]}),n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${a?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),a&&n("div",{className:"absolute right-0 top-full mt-1 w-48 bg-[#2d2d2d] border border-[#444] rounded-lg shadow-lg z-30 py-1",children:Array.from({length:y},(b,v)=>v+1).map(b=>{const v=b===r,N=b<r,w=l===b,C=f[b];return d("div",{onClick:()=>c(w?null:b),className:"cursor-pointer",children:[d("div",{className:`w-full px-3 py-1 flex items-center gap-2 text-left transition-colors hover:bg-[#383838] ${v?"text-cygreen font-medium":N?"text-[#ccc]":"text-[#999]"}`,children:[d("span",{className:"w-5 text-right tabular-nums shrink-0",children:[b,"."]}),n("span",{className:"flex-1",children:m[b]||`Step ${b}`}),C&&n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${w?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),w&&C&&n("div",{className:"px-3 pb-1.5 pl-10",children:n("p",{className:"text-[10px] text-[#888] m-0 leading-relaxed",children:C})})]},b)})})]})]})}function tl(e,t){const[r,s]=P(t??null),[o,a]=P(!1),[i,l]=P((t==null?void 0:t.stale)??!1),c=ce(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(u=>u.json()).then(u=>{s(u),l(!1),a(!1)}).catch(()=>{s({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),l(!1),a(!1)}))},[e]);return{results:r,isRunning:o,runTests:c,stale:i}}function ir({scenarioId:e,screenshotPath:t,updatedAt:r,alt:s,className:o="",imgClassName:a=""}){const[i,l]=P(!1),u=`/api/editor-scenario-image/${t?t.replace(/^screenshots\//,""):`${e}.png`}${r?`?v=${encodeURIComponent(r)}`:""}`;return se(()=>{l(!1)},[e,t]),i?n("div",{className:`flex items-center justify-center ${o}`,children:n("span",{className:"text-[8px] text-gray-500",children:"No img"})}):n("div",{className:o,children:n("img",{src:u,alt:s,className:a,loading:"lazy",onError:()=>l(!0)})})}function fn(e){return e.flatMap(t=>{const r=t.screenshotPaths;return r&&Object.keys(r).length>1?Object.entries(r).map(([s,o])=>({scenario:t,dimensionLabel:s,screenshotPath:o,key:`${t.id}--${s}`})):[{scenario:t,dimensionLabel:null,screenshotPath:t.screenshotPath,key:t.id}]})}function $r({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:o,name:a,dimensionLabel:i,isActive:l,onSelect:c}){const u=e&&s,p=!e&&o;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${a} (${i})`:a,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[u?n(ir,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${a} (${i})`:a,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):p?n("img",{src:o,alt:a,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${a} (${i})`:a})]})}function Sa({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:o,runTests:a,stale:i}=tl(e,r);if(o&&!s)return d("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const u=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[c.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-400":p.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:f,children:f.split(`
|
|
607
|
+
`)[0]},y)))]},p.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:a,disabled:o,className:"text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:o?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!o&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function Fr({filePath:e}){return e?d("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function r5({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:o,focusedEntity:a,onZoomChange:i,analyzedEntities:l=[],glossaryFunctions:c=[],cachedTestResults:u={},activeAnalyzedScenarioId:p,onAnalyzedScenarioSelect:h,entityImports:m,pageFilePaths:f={},onSwitchToBuild:y,entityShaMap:g,structureTab:x="application",onStructureTabChange:b}){const[v,N]=P(""),[w,C]=P(x),S=b?x:w,k=b||C,{pageGroups:T,componentGroups:_}=pe(()=>{var L;const j=new Map,D=new Map;for(const E of e)if(E.componentName){const F=D.get(E.componentName)||[];F.push(E),D.set(E.componentName,F)}else if(So(E.url)){const F=(L=E.url)==null?void 0:L.match(/[?&]c=([^&]+)/),I=F?decodeURIComponent(F[1]):"Isolated",K=D.get(I)||[];K.push(E),D.set(I,K)}else{const F=E.pageFilePath?Ut($t(E.pageFilePath)):Ct(E.url),I=j.get(F)||[];I.push(E),j.set(F,I)}const A=new Map([...D.entries()].sort(([E],[F])=>E.localeCompare(F)));return{pageGroups:j,componentGroups:A}},[e]),$=pe(()=>{const j=new Set((l||[]).filter(A=>A.entityType==="visual").map(A=>A.name)),D=new Map;for(const[A,L]of _)j.has(A)||D.set(A,L);return D},[_,l]),{visualEntities:M,libraryEntities:R}=pe(()=>{const j=l.filter(A=>A.entityType==="visual").sort((A,L)=>A.name.localeCompare(L.name)),D=l.filter(A=>A.entityType==="library"||A.entityType==="functionCall").sort((A,L)=>A.name.localeCompare(L.name));return{visualEntities:j,libraryEntities:D}},[l]),z=pe(()=>{const j=new Set(R.map(D=>D.name));return c.filter(D=>!j.has(D.name)).sort((D,A)=>D.name.localeCompare(A.name))},[c,R]),O=l.some(j=>j.isAnalyzing),U=ye(null),W=ye(0),J=ce(()=>{U.current&&(W.current=U.current.scrollTop)},[]);if(se(()=>{U.current&&W.current>0&&(U.current.scrollTop=W.current)}),e.length===0&&l.length===0&&z.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(o&&a){const j=a.name,D=a.filePath,A=a.sha,L=e.filter(Q=>Q.componentName===j||Q.componentPath===D||!Q.componentName&&(Q.pageFilePath===D||A&&Q.entitySha===A)),E=new Set((m==null?void 0:m[j])||[]),F=E.size>0,I=F?M.filter(Q=>E.has(Q.name)):[],K=F?R.filter(Q=>E.has(Q.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("button",{onClick:()=>i(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:a.displayName})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:L.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):fn(L).map(({scenario:Q,dimensionLabel:V,screenshotPath:Y,key:B})=>n($r,{scenarioId:Q.id,screenshotPath:Y,updatedAt:Q.updatedAt,hasScreenshot:!!Y,name:Q.name,dimensionLabel:V,isActive:Q.id===r,onSelect:()=>s(Q,V??void 0)},B))}),I.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),I.map(Q=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>i(Q.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Q.name})}),n(Fr,{filePath:Q.filePath,projectRoot:t}),(Q.scenarios.length>0||Q.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:Q.scenarios.map(V=>n($r,{imgSrc:V.screenshotPath?`/api/screenshot/${V.screenshotPath}`:null,name:V.name,isActive:V.id===p,onSelect:()=>h==null?void 0:h({analysisId:Q.analysisId,scenarioId:V.id,scenarioName:V.name,entitySha:Q.sha,entityName:Q.name})},V.id))})]},Q.sha))]}),K.length>0&&d("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),K.map(Q=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:Q.name})}),n(Fr,{filePath:Q.filePath,projectRoot:t}),Q.testFile&&n(Sa,{testFile:Q.testFile,entityName:Q.name,cachedResult:u[Q.testFile]})]},Q.sha))]})]})})}return n("div",{ref:U,onScroll:J,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("button",{onClick:()=>k("application"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${S==="application"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Application"}),n("button",{onClick:()=>k("components"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${S==="components"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Components"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:v,onChange:j=>N(j.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),y&&d("button",{onClick:y,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Feature"]})]}),n("div",{className:"border-b border-[#2d2d2d]"}),S==="application"&&T.size>0&&n("div",{children:[...T.entries()].sort(([j],[D])=>j==="Home"?-1:D==="Home"?1:j.localeCompare(D)).filter(([j])=>v.trim()?j.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([j,D])=>{const A=D.some(L=>L.id===r&&!p);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(j,g==null?void 0:g.get(j)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${A?"text-[#D7FF63]":"text-gray-300"}`,children:[j,d("span",{className:`text-xs ${A?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",D.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:A?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),A&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(j,g==null?void 0:g.get(j)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:fn(D).map(({scenario:L,dimensionLabel:E,screenshotPath:F,key:I})=>n($r,{scenarioId:L.id,screenshotPath:F,updatedAt:L.updatedAt,hasScreenshot:!!F,name:L.name,dimensionLabel:E,isActive:L.id===r&&!p,onSelect:()=>s(L,E??void 0)},I))})]},j)})}),S==="components"&&$.size>0&&n("div",{children:[...$.entries()].filter(([j])=>v.trim()?j.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([j,D])=>{const A=D.some(L=>L.id===r&&!p);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(j,g==null?void 0:g.get(j)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${A?"text-[#D7FF63]":"text-gray-300"}`,children:[j,d("span",{className:`text-xs ${A?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",D.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:A?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),A&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(j,g==null?void 0:g.get(j)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:fn(D).map(({scenario:L,dimensionLabel:E,screenshotPath:F,key:I})=>n($r,{scenarioId:L.id,screenshotPath:F,updatedAt:L.updatedAt,hasScreenshot:!!F,name:L.name,dimensionLabel:E,isActive:L.id===r&&!p,onSelect:()=>s(L,E??void 0)},I))})]},j)})}),M.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),O&&e.length===0&&l.every(j=>j.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),M.map(j=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>i(j.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:j.name}),j.isAnalyzing&&j.scenarioCount===0&&d("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Fr,{filePath:j.filePath,projectRoot:t}),(j.scenarios.length>0||j.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[j.scenarios.map(D=>n($r,{imgSrc:D.screenshotPath?`/api/screenshot/${D.screenshotPath}`:null,name:D.name,isActive:D.id===p,onSelect:()=>h==null?void 0:h({analysisId:j.analysisId,scenarioId:D.id,scenarioName:D.name,entitySha:j.sha,entityName:j.name})},D.id)),j.pendingScenarios.map(D=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:D,children:D},D))]})]},j.sha))]}),(R.length>0||z.length>0)&&d("div",{className:`pt-2 mt-1 ${M.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),R.map(j=>d("div",{className:"mt-2",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:j.name}),j.isAnalyzing&&j.scenarioCount===0&&d("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Fr,{filePath:j.filePath,projectRoot:t}),j.testFile?n(Sa,{testFile:j.testFile,entityName:j.name,cachedResult:u[j.testFile]}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},j.sha)),z.map(j=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:j.name})}),n(Fr,{filePath:j.filePath,projectRoot:t}),n(Sa,{testFile:j.testFile,entityName:j.name,cachedResult:u[j.testFile]})]},j.name))]})]})})}function Wp(e){const t={};for(const[r,s]of Object.entries(e))if(typeof s=="string")try{const o=JSON.parse(s);Array.isArray(o)?t[r]=o:typeof o=="object"&&o!==null&&(t[r]=[o])}catch{}else Array.isArray(s)&&(t[r]=s);return t}function Jp(e,t){return e.length===0||t.length===0?!1:e.filter(s=>t.includes(s)).length>=Math.min(e.length,t.length)*.5}function s5(e,t){const{_metadata:r,...s}=t,o=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?Wp(s.localStorage):{},a={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(a[h]=m);const i={},l=[],c=new Set,u=new Set,p=new Set;for(const h of e){const m=h.fields.filter(b=>!b.isRelation),f=m.map(b=>b.name),y=h.name.charAt(0).toLowerCase()+h.name.slice(1);let g=null,x=[];for(const b of[h.name,y,`${y}s`])if(b in s&&Array.isArray(s[b])){g=b,x=s[b],u.add(b);break}if(!g){for(const b of[h.name,y,`${y}s`])if(b in a){g=b,x=a[b],p.add(b),b in o&&c.add(b);break}}if(!g){for(const b of[h.name,y,`${y}s`])if(b in o){g=y,x=o[b],c.add(b);break}}if(!g){for(const[b,v]of Object.entries(o))if(!c.has(b)&&v.length>0&&Jp(f,Object.keys(v[0]))){g=y,x=v,c.add(b);break}}g||(g=y),i[g]=x,l.push({label:h.name,dataKey:g,schemaFields:m.map(b=>({name:b.name,type:b.type,isId:b.isId}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||u.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))p.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function o5(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function a5(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function i5(e,t,r){const s=new Map((r||[]).map(a=>[a.name,a.type])),o={};for(const a of e)o[a]=s.get(a)||(t.length>0?o5(t[0][a]):"text");return o}function l5(e,t){var r;return((r=t==null?void 0:t.find(s=>s.isId))==null?void 0:r.name)||e.find(s=>s==="id")||null}function c5(e,t){const{_metadata:r,...s}=t,o=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?Wp(s.localStorage):{},a={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(a[h]=m);const i={},l=[],c=new Set,u=new Set,p=new Set;for(const h of e){const m=h.name.charAt(0).toLowerCase()+h.name.slice(1),f=h.fields.map(x=>x.name);let y=null,g=[];for(const x of[h.name,m,`${m}s`])if(x in s&&Array.isArray(s[x])){y=x,g=s[x],u.add(x);break}if(!y){for(const x of[h.name,m,`${m}s`])if(x in a){y=x,g=a[x],p.add(x),x in o&&c.add(x);break}}if(!y){for(const x of[h.name,m,`${m}s`])if(x in o){y=m,g=o[x],c.add(x);break}}if(!y){for(const[x,b]of Object.entries(o))if(!c.has(x)&&b.length>0&&Jp(f,Object.keys(b[0]))){y=m,g=b,c.add(x);break}}y||(y=m),i[y]=g,l.push({label:h.name,dataKey:y,category:h.category,description:h.description,schemaFields:h.fields.map(x=>({name:x.name,type:x.type,isId:x.isId??!1}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||u.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))p.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function nl(e){var o,a;const t=new Map,r=new Map;for(const i of e)if(i.componentName){const l=r.get(i.componentName)||[];l.push(i),r.set(i.componentName,l)}else if(So(i.url)){const l=(o=i.url)==null?void 0:o.match(/[?&]c=([^&]+)/),c=l?decodeURIComponent(l[1]):"Isolated",u=r.get(c)||[];u.push(i),r.set(c,u)}else{const l=i.displayName||((a=i.pageFilePath)!=null&&a.startsWith("app/")?Ut($t(i.pageFilePath)):Ct(i.url)),c=t.get(l)||[];c.push(i),t.set(l,c)}const s=new Map([...r.entries()].sort(([i],[l])=>i.localeCompare(l)));return{pageGroups:t,componentGroups:s}}function Hp(e,t){var s,o;const r=new Map;for(const[a,i]of e){const l=(s=i.find(c=>c.entitySha))==null?void 0:s.entitySha;l&&r.set(a,l)}for(const[a,i]of t){const l=(o=i.find(c=>c.entitySha))==null?void 0:o.entitySha;l&&r.set(a,l)}return r}function d5(e){const t=new Set;for(const[r,s]of Object.entries(e)){t.add(r);for(const o of s)t.add(o)}return t}function u5(e,t,r,s){if(t.has(e))return!0;const o=r.find(a=>a.sha===e);return o?s.has(o.name):!1}function p5(e,t,r,s){const o=[];for(const[a,i]of e){const l=r.get(a);l?s(l)||o.push({name:a,scenarios:i,reason:"incomplete"}):o.push({name:a,scenarios:i,reason:"missing"})}for(const[a,i]of t){const l=r.get(a);l?s(l)||o.push({name:a,scenarios:i,reason:"incomplete"}):o.push({name:a,scenarios:i,reason:"missing"})}return o}function Xc(e,t,r){if(!e)return null;const s=t.find(o=>o.sha===e);return s?{sha:e,name:s.name,filePath:s.filePath,entityType:s.entityType,displayName:s.name}:null}const ed=120;function Vp({text:e,theme:t}){const[r,s]=P(!1),o=e.length>ed,a=o&&!r?e.slice(0,ed)+"…":e,i=t==="light";return d("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),d("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[a,o&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}const td={new:0,edited:1,impacted:2};function nd({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function rd({filePath:e}){const[t,r]=P(null),[s,o]=P(!0),[a,i]=P(null);return se(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),se(()=>{o(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>o(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!a?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(a,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function sd({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?d(ve,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?d(ve,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function od({scenarioId:e,screenshotPath:t,name:r,dimensionLabel:s,isActive:o,onSelect:a,updatedAt:i}){const l=ye(null);return se(()=>{o&&l.current&&l.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[o]),d("button",{ref:l,onClick:a,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:s?`${r} (${s})`:r,children:[d("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all relative ${o?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:[n(ir,{scenarioId:e,screenshotPath:t,updatedAt:i,alt:s?`${r} (${s})`:r,className:"w-full h-full bg-white",imgClassName:"w-full h-full object-contain bg-white"}),s&&n("span",{className:"absolute bottom-1 right-1 text-[9px] font-medium bg-black/60 text-white px-1.5 py-0.5 rounded",children:s})]}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${o?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:s?`${r} (${s})`:r})]})}function h5({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Va({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:o,runTests:a,stale:i}=tl(e,r);if(o&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const u=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-600":p.status==="failed"?"text-red-500":"text-gray-400"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:f,children:f.split(`
|
|
608
|
+
`)[0]},y)))]},p.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:a,disabled:o,className:"text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:o?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!o&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function ad(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function id(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,c;const o=((l=t[r])==null?void 0:l.status)||"impacted",a=((c=t[s])==null?void 0:c.status)||"impacted",i=(td[o]??2)-(td[a]??2);return i!==0?i:r.localeCompare(s)})}function m5({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],cachedTestResults:s={},projectRoot:o,activeScenarioId:a,onScenarioSelect:i,onClose:l,entityChangeStatus:c={},modifiedFiles:u=[],featureName:p,userPrompt:h}){const m=pe(()=>{if(t.length===0||Object.keys(c).length===0)return e;const $=new Set(e.map(R=>R.id)),M=t.filter(R=>{var O,U;if($.has(R.id))return!1;const z=R.componentName||R.displayName||((O=R.pageFilePath)!=null&&O.startsWith("app/")?Ut($t(R.pageFilePath)):Ct(R.url));return((U=c[z])==null?void 0:U.status)==="impacted"});return M.length===0?e:[...e,...M]},[e,t,c]),f=pe(()=>Object.entries(c).filter(([,$])=>$.status==="new"||$.status==="edited").map(([$,M])=>({name:$,status:M.status})),[c]),[y,g]=P(null),x=ce($=>{g(M=>M===$?null:$)},[]),{pageGroups:b,componentGroups:v}=pe(()=>nl(m),[m]),N=pe(()=>id([...b.entries()],c),[b,c]),w=pe(()=>id([...v.entries()],c),[v,c]),C=N,S=w,k=pe(()=>wy(r,c),[r,c]),T=pe(()=>{const $=[];for(const[,M]of C)$.push(...M);for(const[,M]of S)$.push(...M);return $},[C,S]),_=ye(!1);return se(()=>{_.current||T.length!==0&&(_.current=!0,console.log("[ResultsPanel] Auto-selecting first scenario: %s",T[0].name),i(T[0]))},[T,i]),se(()=>{if(T.length===0)return;const $=M=>{if(M.key!=="ArrowLeft"&&M.key!=="ArrowRight")return;const R=M.target,z=R==null?void 0:R.tagName;if(z==="INPUT"||z==="SELECT"||z==="TEXTAREA"&&!R.classList.contains("xterm-helper-textarea"))return;M.preventDefault();const O=T.findIndex(W=>W.id===a);let U;M.key==="ArrowLeft"?U=O<=0?T.length-1:O-1:U=O>=T.length-1?0:O+1,i(T[U])};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[T,a,i]),m.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:l,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),p&&n("div",{className:"text-[11px] text-gray-400 truncate",title:p,children:p})]}),n("button",{onClick:l,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),h&&n(Vp,{text:h,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:d("div",{className:"space-y-5",children:[C.length>0&&d("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:C.map(([$,M])=>{var U;const R=c[$],z=y===$,O=(U=M[0])==null?void 0:U.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:$}),R&&n(nd,{status:R,onClick:()=>x($)})]}),z&&(R==null?void 0:R.status)==="edited"&&O&&n(rd,{filePath:O}),z&&(R==null?void 0:R.status)==="impacted"&&n(sd,{impactedBy:R.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:fn(M).map(({scenario:W,dimensionLabel:J,screenshotPath:j,key:D})=>n(od,{scenarioId:W.id,screenshotPath:j,name:ad(W.name),dimensionLabel:J,isActive:W.id===a,onSelect:()=>i(W,J??void 0),updatedAt:W.updatedAt},D))})]},$)})})]}),S.length>0&&d("div",{className:C.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:S.map(([$,M])=>{var U;const R=c[$],z=y===$,O=(U=M[0])==null?void 0:U.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:$}),R&&n(nd,{status:R,onClick:()=>x($)})]}),z&&(R==null?void 0:R.status)==="edited"&&O&&n(rd,{filePath:O}),z&&(R==null?void 0:R.status)==="impacted"&&n(sd,{impactedBy:R.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:fn(M).map(({scenario:W,dimensionLabel:J,screenshotPath:j,key:D})=>n(od,{scenarioId:W.id,screenshotPath:j,name:ad(W.name),dimensionLabel:J,isActive:W.id===a,onSelect:()=>i(W,J??void 0),updatedAt:W.updatedAt},D))})]},$)})})]}),k.length>0&&d("div",{className:C.length>0||S.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:k.map($=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:$.name})}),n(h5,{filePath:$.filePath,projectRoot:o}),$.testFile?n(Va,{testFile:$.testFile,entityName:$.name,cachedResult:s[$.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},$.name))})]}),u.length>0&&d("div",{className:C.length>0||S.length>0||k.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",u.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:u.map($=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${$.status==="added"||$.status==="untracked"?"text-green-600":$.status==="modified"?"text-blue-600":$.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:$.status==="added"||$.status==="untracked"?"A":$.status==="modified"?"M":$.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:$.path})]},$.path))})]})]})})]})}function ld(e,t,r,s){var c;const o=s.length>0?s.map(u=>`- "${u.name}" (ID: ${u.id})${u.url?` — URL: ${u.url}`:""}`).join(`
|
|
609
|
+
`):"(no scenarios yet)",a=t.endsWith("/page.tsx")||t.endsWith("/page.js"),i=((c=s.find(u=>u.url))==null?void 0:c.url)||"/",l=[`You are helping edit scenarios for the "${e}" entity in a CodeYam project.`,"","## Entity",`- **Name:** ${e}`,`- **File:** ${t}`,`- **Type:** ${a?"Page (application scenario with seed data)":"Component (component scenario with mock props)"}`,"","## Existing Scenarios",o,""];return a?l.push("## How Seed Data Works","","Application scenarios use `seed` data to populate the database before the page is captured.","The seed is a JSON object where each key is a Prisma model name in camelCase singular (matching the Prisma client accessor name) and the value is an array of records.","","### Seed Key Naming Convention","The key must be the camelCase singular form of the Prisma model name:",'- `model User` → key `"user"`','- `model BlogPost` → key `"blogPost"`','- `model Feedback` → key `"feedback"`',"",'**WARNING:** Do NOT use plural forms like "users", "blogPosts", or "feedbacks" — the seed adapter will silently fail to match them.',"","To understand the data models, read the Prisma schema at `prisma/schema.prisma`.","To see examples of existing seed data, look at `.codeyam/editor-scenarios/*.seed.json` files.","",`Also read the source file at \`${t}\` to understand what data the page queries and renders.`,"","## Registering a Scenario","","For small seed data, pass it inline:","```",`codeyam editor register '{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}'`,"```","","For large seed data, write it to a temp file and use @file syntax:","```","# Write JSON to a temp file","cat > .codeyam/tmp/scenario.json << 'SCENARIO_EOF'",`{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}`,"SCENARIO_EOF","codeyam editor register @.codeyam/tmp/scenario.json","```"):l.push("## Registering a Scenario","",`Read the source file at \`${t}\` to understand what props the component expects.`,"","```",`codeyam editor register '{"name":"Scenario Name","type":"component","componentName":"${e}","componentPath":"${t}","dimensions":["Laptop"],"mockData":{"propName":"value"}}'`,"```"),l.push("","## Deleting a Scenario","","To delete a scenario, use its ID from the list above:","```","codeyam editor delete <scenarioId>","```","","## Validating Seed Data","","Before registering, you can validate seed data structure and check that keys match Prisma models:","```",`codeyam editor validate-seed '{"user":[...]}'`,"```"),l.push("","## Recapturing Scenarios After Code Changes","",`If the user asks you to modify the code for this ${a?"page":"component"} (CSS, layout, logic, etc.), you MUST re-register all existing scenarios after the code change so their screenshots are updated.`,"","Re-registering a scenario with the same name overwrites it and captures a fresh screenshot.","","To recapture, re-register each existing scenario using `codeyam editor register` with its current configuration. You can read the scenario JSON files in `.codeyam/editor-scenarios/` to get the exact registration data for each scenario."),l.push("","## Important","- DO NOT take any action until the user tells you what they want","- Start by briefly listing the existing scenarios",'- Then ask: "Would you like to modify an existing scenario or add a new one?"',"- Wait for the user's answer before proceeding",'- Keep scenario names descriptive: "Empty State", "With Comments", "Admin View", etc.',`- Each scenario should capture a distinct, meaningful state of the ${a?"page":"component"}`),l.join(`
|
|
610
|
+
`)}function Kp(e,t){var o;const r=t.some(a=>!a.componentName),s=t.map(a=>`'${a.id}'`).join(", ");if(r){const a=((o=t.find(l=>l.url))==null?void 0:o.url)||null,i=t.map(l=>`.codeyam/editor-scenarios/${l.id}.json`).join(", ");return[`### Page: "${e}" (${t.length} scenario(s))`,...a?["",`Scenario URL: \`${a}\``]:[],"",...a?["Step A: Find the source file that renders this page. In Next.js App Router, URLs map to page.tsx files:"," - `/` → `app/page.tsx`"," - `/about` → `app/about/page.tsx`"," - `/c/my-slug` → `app/c/[slug]/page.tsx` (dynamic segment)","",`Based on the URL \`${a}\`, find the corresponding page.tsx file. Confirm it exists with \`cat <filepath> | head -5\`.`]:["Step A: Find the source file that renders this page by running:",' find src app -name "App.tsx" -o -name "App.jsx" -o -name "page.tsx" -o -name "page.jsx" -o -name "index.tsx" 2>/dev/null',"","Pick the file that is the main app entry point or the page component for this route. Confirm it exists with `cat <filepath> | head -5`."],"","Step B: Set page_file_path on all scenarios for this page (replace PAGE_FILE_PATH with the path from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET page_file_path = 'PAGE_FILE_PATH' WHERE id IN (${s});"`,"","Step C: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE file_path = 'PAGE_FILE_PATH' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, the path was wrong — go back to Step A.","","Step D: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step C):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`,"","Step E: Add pageFilePath to the scenario JSON files so this fix persists across clones.",`For each file (${i}), read it and add \`"pageFilePath": "PAGE_FILE_PATH"\` to the \`_metadata\` object (after the \`"type"\` field). Then commit the updated JSON files.`].join(`
|
|
611
|
+
`)}else return[`### Component: "${e}" (${t.length} scenario(s))`,"","Step A: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE name = '${e}' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, check that .codeyam/glossary.json contains an entry for this component.","","Step B: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`].join(`
|
|
612
|
+
`)}function Us({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:o,name:a,dimensionLabel:i,isActive:l,onSelect:c}){const u=e&&s,p=!e&&o;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${a} (${i})`:a,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[u?n(ir,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${a} (${i})`:a,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):p?n("img",{src:o,alt:a,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${a} (${i})`:a})]})}function Rs({filePath:e}){return e?d("div",{className:"flex items-center gap-1.5 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1.5 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-sm truncate font-['IBM_Plex_Mono']",children:e}),n("svg",{className:"shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:12,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Gp({name:e,scenarios:t,reason:r="missing"}){var a,i;const s=((a=t[0])==null?void 0:a.componentPath)||((i=t[0])==null?void 0:i.pageFilePath)||null,o=r==="incomplete"?[`The "${e}" entity exists but has not been fully analyzed — its components and functions cannot be displayed.`,"","Follow these steps:","",`Step 1: Check if "${e}" is in the glossary:`,` cat .codeyam/glossary.json | grep "${e}"`,"","If not found, add an entry to .codeyam/glossary.json:",` { "name": "${e}", "filePath": "${s||"FILL_IN_PATH"}", "description": "...", "returnType": "JSX.Element" }`,"","Step 2: Run: codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
|
|
613
|
+
`):[`The "${e}" ${t.some(l=>!l.componentName)?"page":"component"} is missing entity data in the CodeYam database. Its scenarios are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","","Step 1: Run: codeyam editor analyze-imports","","Step 2: Fix this entity:","",Kp(e,t),"","Step 3: Reload the editor page in the browser and verify the scenarios appear."].join(`
|
|
614
|
+
`);return n(xt,{content:o,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-[#E0D400] hover:text-[#E0D400]/80 bg-transparent border border-[#E0D400]/30 rounded px-2 py-0.5 cursor-pointer transition-colors ml-2"})}function f5({brokenEntities:e}){const[t,r]=P(!1),s=ce(c=>{navigator.clipboard.writeText(c).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})},[]);if(e.length===0)return null;const o=e.reduce((c,u)=>c+u.scenarios.length,0),a=e.filter(c=>c.reason==="incomplete"),i=e.filter(c=>c.reason==="missing"),l=[`${e.length} entities are missing data in the CodeYam database. ${o} total scenario(s) are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","",...a.length>0?["## Step 1: Add missing entries to the glossary","","Read `.codeyam/glossary.json` and check if these entities have entries. For each one that is missing, add an entry:","",...a.map(c=>{var p,h;const u=((p=c.scenarios[0])==null?void 0:p.componentPath)||((h=c.scenarios[0])==null?void 0:h.pageFilePath)||"FILL_IN_PATH";return`- "${c.name}" (filePath: "${u}")`}),"",'Each glossary entry needs: name, filePath, description, returnType (use "JSX.Element" for components/pages).',""]:["## Step 1: No glossary changes needed",""],"## Step 2: Run import analysis"," codeyam editor analyze-imports","",...i.length>0?["## Step 3: Fix missing entity associations","",...i.map(c=>Kp(c.name,c.scenarios)),""]:[],`## Step ${i.length>0?"4":"3"}: Reload the editor page in the browser and verify all scenarios appear. Then commit the updated scenario JSON files so the fix persists across clones.`].join(`
|
|
615
|
+
`);return n("div",{className:"p-4 rounded-lg border border-[#E0D400]/40 bg-[#E0D400]/8",children:d("div",{className:"flex items-center gap-3",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),d("p",{className:"flex-1 min-w-0 text-sm text-[#E0D400]/90 m-0 leading-snug font-['IBM_Plex_Sans']",children:[e.length," ",e.length===1?"entity is":"entities are"," missing data, resulting in ",o," hidden scenario",o!==1?"s":"","."," ",n("button",{type:"button",className:"font-bold underline bg-transparent border-none text-[#E0D400] cursor-pointer p-0 text-sm inline hover:text-[#E0D400]/70 transition-colors",onClick:()=>s(l),children:t?d("span",{className:"inline-flex items-center gap-1",children:["Copied",n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"inline",children:n("polyline",{points:"20 6 9 17 4 12"})})]}):"Copy this prompt"})," ","into Claude to fix them all at once."]}),n(xt,{content:l,label:d("span",{className:"flex items-center gap-2",children:["COPY PROMPT",d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]}),copiedLabel:d("span",{className:"flex items-center gap-2",children:[n("span",{className:"invisible",children:"COPY PROMPT"}),n("span",{className:"absolute inset-0 flex items-center justify-center",children:"COPIED!"}),n("span",{className:"invisible",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",children:n("rect",{x:"9",y:"9",width:"13",height:"13"})})})]}),className:"relative text-xs font-semibold text-[#1e1e1e] bg-[#E0D400] hover:bg-[#E0D400]/80 border-none rounded px-4 py-2 cursor-pointer transition-colors shrink-0 tracking-wide font-['IBM_Plex_Mono']"})]})})}function qp({focusedEntity:e,breadcrumbItems:t,onZoomChange:r,projectRoot:s,scenarios:o,analyzedEntities:a,activeScenarioId:i,onScenarioSelect:l,onAnalyzedScenarioSelect:c,onSwitchToBuild:u,entityImports:p,glossaryFunctions:h,cachedTestResults:m={},glossaryEntries:f,entityShaMap:y,componentGroups:g,visualEntities:x,isEntityComplete:b,onReseedPreview:v}){var Ee;const N=e.filePath,w=e.name,[C,S]=P("scenarios"),[k,T]=P(null),[_,$]=P(""),[M,R]=P(!1),[z,O]=P(null),[U,W]=P(!1),[J,j]=P(!1),[D,A]=P(null);se(()=>{S("scenarios"),T(null),W(!1),j(!1),A(null)},[e.sha]);const L=pe(()=>{const X=new Map;for(const fe of h)X.set(fe.name,fe);return X},[h]),E=a.some(X=>X.sha===e.sha||X.filePath===N),F=!!((Ee=p==null?void 0:p[w])!=null&&Ee.length),I=ce(async X=>{if(!(!_.trim()||M)){R(!0);try{(await fetch("/api/editor-rename-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:X,name:_.trim()})})).ok&&T(null)}catch{}finally{R(!1)}}},[_,M]),K=ce(async X=>{if(confirm(`Delete scenario "${X.name}"?`)){O(X.id);try{const fe=X.screenshotPaths?Object.values(X.screenshotPaths):X.screenshotPath?[X.screenshotPath]:[];await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:X.id,screenshotPaths:fe})})}catch{}finally{O(null)}}},[]);if(!E&&!F){const X=o.filter(ae=>ae.entitySha===e.sha),fe=[`The "${e.displayName}" entity (${N}) exists in the database but has not been fully analyzed. Its components and functions cannot be shown until it has import metadata.`,"","Follow these steps:","",`Step 1: Add "${w}" to the glossary if it's not already there:`,` Check: cat .codeyam/glossary.json | grep "${w}"`,"",` If not found, add an entry with name "${w}" and filePath "${N}" to .codeyam/glossary.json`,"","Step 2: Run import analysis:"," codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
|
|
616
|
+
`);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>{if(t.length>1){const ae=t[t.length-2];r(ae.componentName,ae.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-lg",title:"Go back",children:"←"}),n("h2",{className:"text-lg font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),N&&n(Rs,{filePath:N,projectRoot:s}),d("div",{className:"py-2",children:[n("p",{className:"text-[11px] text-amber-400/80 m-0 leading-relaxed",children:"This entity has not been fully analyzed. Its components and functions cannot be displayed. Please copy and paste this prompt into Claude to fix the data."}),n("div",{className:"mt-2",children:n(xt,{content:fe,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-2 py-1 cursor-pointer transition-colors"})})]}),X.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:fn(X).map(({scenario:ae,dimensionLabel:ie,screenshotPath:he,key:Te})=>n(Us,{scenarioId:ae.id,screenshotPath:he,updatedAt:ae.updatedAt,hasScreenshot:!!he,name:ae.name,dimensionLabel:ie,isActive:ae.id===i,onSelect:()=>l(ae,ie??void 0)},Te))})]})})}const Q=e.sha,V=o.filter(X=>!X.componentName&&(X.pageFilePath===N||Q&&X.entitySha===Q)),Y=o.filter(X=>X.componentName===w||X.componentPath===N),B=x.find(X=>X.filePath===N||X.name===w),H=L.get(w)||h.find(X=>X.filePath===N),ne=[...V,...Y],oe=pe(()=>{const X=[];if(X.push(`# Create a New Scenario for "${e.displayName}"`),X.push(""),X.push(`**Entity**: ${e.displayName}`),X.push(`**Type**: ${e.entityType}`),X.push(`**File**: ${N}`),X.push(""),ne.length>0){X.push("## Existing Scenarios");for(const fe of ne)X.push(`- **${fe.name}**${fe.url?` — URL: ${fe.url}`:""}`);X.push("")}return X.push("## Your Task"),X.push("Ask the user what scenario they would like to create. Offer two options:"),X.push("1. **Describe a scenario** — the user tells you what they want and you create it"),X.push("2. **Analyze gaps** — you review the existing scenarios and source code to suggest scenarios that would improve coverage"),X.push(""),X.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),X.join(`
|
|
617
|
+
`)},[e.displayName,e.entityType,N,ne]),Z=new Set((p==null?void 0:p[w])||[]),re=F?[...g.entries()].filter(([X])=>Z.has(X)):[],ue=F?x.filter(X=>Z.has(X.name)&&!re.some(([fe])=>fe===X.name)):[],we=F?f.filter(X=>Z.has(X.name)&&X.returnType!=="JSX.Element"&&X.returnType!=="React.ReactNode").map(X=>({name:X.name,filePath:X.filePath,description:X.description||"",testFile:X.testFile,feature:X.feature})):[],je=re.length>0||ue.length>0,be=we.length>0;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-5",children:[d("div",{className:"mb-5",children:[d("div",{className:"flex items-center gap-2.5",children:[n("button",{onClick:()=>{if(t.length>1){const X=t[t.length-2];r(X.componentName,X.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-xl",title:"Go back",children:"←"}),n("h2",{className:"text-xl font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),e.filePath&&n("div",{className:"mt-1.5 ml-7",children:n(Rs,{filePath:e.filePath,projectRoot:s})})]}),n("div",{className:"-mx-5 px-5 border-t border-b border-[#3d3d3d] flex items-center gap-6",children:[["scenarios","Scenarios"],["components","Components"],["functions","Functions"],["data-structure","Data Structure"]].map(([X,fe])=>n("button",{onClick:()=>S(X),className:`text-xs font-normal uppercase tracking-wider transition-colors bg-transparent border-none cursor-pointer px-0 font-['IBM_Plex_Mono'] border-b-2 leading-none ${C===X?"text-[#D7FF63] border-b-[#D7FF63]":"text-gray-500 hover:text-gray-300 border-b-transparent"}`,style:{marginBottom:-1,paddingTop:16,paddingBottom:14},children:fe},X))}),C==="scenarios"&&d("div",{className:"space-y-3 mt-5",children:[ne.map(X=>{const fe=X.id===i,ae=k===X.id;return d("div",{children:[d("div",{onClick:()=>{ae||l(X)},className:`flex items-center gap-4 p-3 rounded-lg cursor-pointer transition-colors ${fe?"bg-[#1a2e1a] border border-[#D7FF63]/40":"bg-[#252525] hover:bg-[#2a2a2a] border border-transparent"}`,style:{opacity:z===X.id?.4:1},children:[X.screenshotPaths&&Object.keys(X.screenshotPaths).length>1?n("div",{className:"flex gap-2 shrink-0",children:Object.entries(X.screenshotPaths).map(([ie,he])=>d("div",{className:"relative",children:[n(ir,{scenarioId:X.id,screenshotPath:he,updatedAt:X.updatedAt,alt:ie,className:"rounded w-[120px] h-[75px] overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}),n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:ie})]},ie))}):X.screenshotPath?n(ir,{scenarioId:X.id,screenshotPath:X.screenshotPath,updatedAt:X.updatedAt,alt:"",className:"rounded w-[160px] h-[100px] shrink-0 overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}):n("div",{className:"rounded bg-[#1a1a1a] w-[160px] h-[100px] shrink-0 flex items-center justify-center border border-[#3d3d3d]",children:n("span",{className:"text-[10px] text-gray-600",children:"No image"})}),n("div",{className:"flex-1 min-w-0",children:ae?d("form",{className:"flex items-center gap-1.5",onSubmit:ie=>{ie.preventDefault(),I(X.id)},onClick:ie=>ie.stopPropagation(),children:[n("input",{type:"text",value:_,onChange:ie=>$(ie.target.value),className:"flex-1 px-2 py-1 text-xs bg-[#1e1e1e] text-white border border-[#3d3d3d] rounded outline-none focus:border-[#005c75] min-w-0",autoFocus:!0,disabled:M}),n("button",{type:"submit",disabled:M||!_.trim(),className:"px-2 py-1 text-[10px] bg-[#005c75] text-white rounded hover:bg-[#004d63] disabled:opacity-40 cursor-pointer border-none",children:M?"...":"Save"}),n("button",{type:"button",onClick:()=>T(null),className:"px-2 py-1 text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none",children:"Cancel"})]}):d(ve,{children:[n("span",{className:"text-xs text-gray-300 truncate block",children:X.name}),fe&&d("div",{className:"flex items-center gap-3 mt-1.5",children:[n("button",{onClick:ie=>{ie.stopPropagation(),A(D===X.id?null:X.id)},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 cursor-pointer bg-transparent border-none p-0",children:"View Data"}),n("button",{onClick:ie=>{ie.stopPropagation(),j(!1),W(!0)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Edit with Claude"}),n("button",{onClick:ie=>{ie.stopPropagation(),T(X.id),$(X.name)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n("button",{onClick:ie=>{ie.stopPropagation(),K(X)},disabled:z===X.id,className:"text-[10px] text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})]})})]}),D===X.id&&n(g5,{scenarioId:X.id,onClose:()=>A(null),editPrompt:ld(e.displayName,e.filePath,e.entityType,ne),onReseedPreview:v})]},X.id)}),B&&(B.scenarios.length>0||B.pendingScenarios.length>0)&&d("div",{className:"space-y-1 mt-2",children:[B.scenarios.map(X=>d("div",{onClick:()=>c({analysisId:B.analysisId,scenarioId:X.id,scenarioName:X.name,entitySha:B.sha,entityName:B.name}),className:"flex items-center gap-3 p-2 rounded cursor-pointer transition-colors hover:bg-[#252525] border border-transparent",children:[X.screenshotPath?n("img",{src:`/api/screenshot/${X.screenshotPath}`,alt:X.name,className:"rounded w-[48px] h-[48px] shrink-0 object-cover",loading:"lazy"}):n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),n("span",{className:"text-xs text-gray-300 truncate",children:X.name})]},X.id)),B.pendingScenarios.map(X=>d("div",{className:"flex items-center gap-3 p-2",children:[n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"..."})}),n("span",{className:"text-xs text-gray-500 truncate",children:X})]},X))]}),ne.length===0&&!B&&!H&&n("div",{className:"text-xs text-gray-500 py-2",children:"No scenarios for this entity"}),d("button",{onClick:()=>{W(!1),j(!0)},className:"flex items-center gap-2.5 mt-4 text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 font-normal uppercase tracking-wider font-['IBM_Plex_Mono'] transition-colors",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),n("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),"Create New Scenario"]}),J&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:oe,height:500,onClose:()=>j(!1)})}),U&&ne.length>0&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:ld(e.displayName,e.filePath,e.entityType,ne),height:500,onClose:()=>W(!1)})})]}),C==="components"&&n("div",{className:"space-y-3",children:je?d(ve,{children:[re.map(([X,fe])=>n("div",{children:y.has(X)?d(ve,{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X,y.get(X)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X})}),fe.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:fn(fe).map(({scenario:ae,dimensionLabel:ie,screenshotPath:he,key:Te})=>n(Us,{scenarioId:ae.id,screenshotPath:he,updatedAt:ae.updatedAt,hasScreenshot:!!he,name:ae.name,dimensionLabel:ie,isActive:ae.id===i,onSelect:()=>l(ae,ie??void 0)},Te))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-[11px] font-medium text-gray-500",children:X}),n("p",{className:"text-[10px] text-amber-400/80 m-0 mt-1.5 leading-relaxed",children:"There is data missing that is required to show the scenarios for this component. Please copy and paste this prompt into Claude to ask Claude to fix the data."}),n("div",{className:"mt-1.5",children:n(Gp,{name:X,scenarios:fe})})]})},X)),ue.map(X=>d("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X.name,X.sha),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X.name})}),(X.scenarios.length>0||X.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[X.scenarios.map(fe=>n(Us,{imgSrc:fe.screenshotPath?`/api/screenshot/${fe.screenshotPath}`:null,name:fe.name,isActive:!1,onSelect:()=>c({analysisId:X.analysisId,scenarioId:fe.id,scenarioName:fe.name,entitySha:X.sha,entityName:X.name})},fe.id)),X.pendingScenarios.map(fe=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:fe,children:fe},fe))]})]},X.sha))]}):n("div",{className:"text-xs text-gray-500 py-2",children:"No component dependencies"})}),C==="functions"&&d("div",{className:"space-y-3",children:[H&&H.testFile&&d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(Rs,{filePath:H.testFile,projectRoot:s})]}),n(Va,{testFile:H.testFile,entityName:w,cachedResult:m[H.testFile]})]}),be?n("div",{children:we.map(X=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X.name,y.get(X.name)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X.name})}),n(Rs,{filePath:X.filePath,projectRoot:s}),X.testFile&&d("div",{className:"mt-0.5",children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:X.testFile})]}),n(Va,{testFile:X.testFile,entityName:X.name,cachedResult:m[X.testFile]})]})]},X.name))}):H!=null&&H.testFile?null:n("div",{className:"text-xs text-gray-500 py-2",children:"No function dependencies"})]}),C==="data-structure"&&n(y5,{})]})})}function g5({scenarioId:e,onClose:t,editPrompt:r,onReseedPreview:s}){const[o,a]=P(null),[i,l]=P([]),[c,u]=P(!0),[p,h]=P(null),[m,f]=P(null),[y,g]=P(!1),[x,b]=P(null),[v,N]=P(""),[w,C]=P(""),[S,k]=P(0),[T,_]=P(!1),[$,M]=P(!1),R=ye(null);if(se(()=>{u(!0),h(null),Promise.all([fetch("/api/editor-schema").then(A=>A.json()).catch(()=>({models:[]})),fetch(`/api/editor-scenario-data?scenarioId=${e}`).then(A=>A.json())]).then(([A,L])=>{const E=A.source==="explicit"?c5(A.dataStructures||[],L):s5(A.models||[],L);a(E.data),l(E.tabs),E.tabs.length>0&&!m&&f(E.tabs[0].dataKey)}).catch(()=>h("Failed to load scenario data")).finally(()=>u(!1))},[e,S]),c)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-400",children:"Loading mock data..."});if(p||!o)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-red-400",children:p||"No data available"});if(i.length===0)return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-500",children:["No mock data found for this scenario.",n("button",{onClick:t,className:"ml-2 text-gray-400 hover:text-white bg-transparent border-none cursor-pointer text-[10px]",children:"Dismiss"})]});const z=i.find(A=>A.dataKey===m)||i[0],O=m?o[m]||[]:[],U=a5(O,z.schemaFields),W=i5(U,O,z.schemaFields),J=l5(U,z.schemaFields);return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-[#252525] border-b border-[#3d3d3d] flex-wrap",children:[i.map(A=>{const L=m===A.dataKey,E=A.category==="datastore"?L?"text-[#D7FF63] bg-[#D7FF63]/15 border-[#D7FF63]/40":"text-[#D7FF63]/60 bg-transparent border-transparent hover:text-[#D7FF63]/80":A.category==="mock-api"?L?"text-blue-400 bg-blue-400/15 border-blue-400/40":"text-blue-400/60 bg-transparent border-transparent hover:text-blue-400/80":L?"text-white bg-[#3d3d3d] border-[#4d4d4d]":"text-gray-500 bg-transparent border-transparent hover:text-gray-300";return n("button",{onClick:()=>f(A.dataKey),className:`px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider rounded cursor-pointer border transition-colors ${E}`,children:A.label},A.dataKey)}),n("div",{className:"flex-1"}),n("button",{onClick:t,className:"w-5 h-5 flex items-center justify-center text-gray-500 hover:text-white bg-[#3d3d3d] hover:bg-[#4d4d4d] rounded-full border-none cursor-pointer text-xs transition-colors",title:"Close",children:"×"})]}),(z.description||z.category)&&d("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[#1e1e1e] border-b border-[#2d2d2d]",children:[z.category&&n("span",{className:`text-[9px] rounded px-1.5 py-0 border ${z.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":z.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border-blue-400/30":"text-gray-400 bg-gray-700/30 border-gray-600/30"}`,children:z.category==="mock-api"?"API Mock":z.category}),z.description&&n("span",{className:"text-[10px] text-gray-500",children:z.description})]}),U.length===0?n("div",{className:"px-3 py-4 text-[10px] text-gray-500 text-center",children:"No columns defined for this table"}):n("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:d("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n("thead",{children:d("tr",{className:"bg-[#1e1e1e] sticky top-0 z-10",children:[n("th",{className:"text-right text-gray-600 font-normal px-2 py-1.5 border-b border-[#3d3d3d] w-8",children:"#"}),U.map(A=>d("th",{className:"text-left px-2 py-1.5 border-b border-[#3d3d3d] whitespace-nowrap overflow-hidden",children:[A===J&&n("span",{className:"inline-block text-[8px] font-bold text-white bg-[#D7FF63] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n("span",{className:"text-gray-300 font-medium",children:A}),n("span",{className:"text-gray-600 font-normal ml-1",children:W[A]})]},A))]})}),n("tbody",{children:O.map((A,L)=>d("tr",{className:"border-b border-[#2d2d2d] hover:bg-[#252525] group/row",children:[n("td",{className:"text-right text-gray-600 px-2 py-1.5 w-8 select-none",children:L+1}),U.map(E=>d("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${E===J?"text-[#D7FF63] font-medium":"text-gray-300"}`,title:String(A[E]??""),children:[n("span",{className:"truncate block whitespace-nowrap",children:A[E]===null?n("span",{className:"text-gray-600 italic",children:"null"}):typeof A[E]=="object"?n("span",{className:"text-gray-500",children:JSON.stringify(A[E])}):typeof A[E]=="number"?n("span",{className:"text-amber-400",children:String(A[E])}):String(A[E])}),n("button",{onClick:F=>{F.stopPropagation(),b({row:L,col:E});const I=A[E]===null?"":typeof A[E]=="object"?JSON.stringify(A[E]):String(A[E]);N(I),C(I)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-gray-500 hover:text-white bg-[#252525] border border-[#4d4d4d] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:d("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},E))]},L))})]})}),x&&d("div",{className:"border-t border-[#3d3d3d] bg-[#1e1e1e] px-3 py-2",children:[n("div",{className:"flex items-center gap-2 mb-1.5",children:d("span",{className:"text-[10px] text-gray-400",children:["Editing"," ",n("strong",{className:"text-gray-200",children:x.col})," in row ",x.row+1]})}),n("textarea",{value:v,onChange:A=>{const L=A.target.value;N(L),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{D(z.dataKey,x.row,x.col,L)},600)},className:"w-full px-2 py-1.5 text-[11px] bg-[#252525] text-white border border-[#4d4d4d] rounded outline-none focus:border-[#D7FF63]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:v.length>100?4:2,onKeyDown:A=>{A.key==="Escape"&&j(),A.key==="Enter"&&(A.metaKey||A.ctrlKey)&&(R.current&&clearTimeout(R.current),D(z.dataKey,x.row,x.col,v),b(null))}}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[n("button",{onClick:()=>{R.current&&clearTimeout(R.current),D(z.dataKey,x.row,x.col,v),b(null)},className:"px-3 py-1 text-[10px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded cursor-pointer border-none hover:bg-[#D7FF63]/80 transition-colors",children:"Save"}),n("button",{onClick:()=>j(),className:"px-3 py-1 text-[10px] text-gray-400 hover:text-white bg-transparent border-none cursor-pointer",children:"Cancel"}),d("span",{className:"text-[9px] text-gray-600 ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]}),T&&!x&&d("div",{className:"border-t border-[#3d3d3d] bg-amber-500/5 px-3 py-2 flex items-center gap-2",children:[n("span",{className:"text-[10px] text-amber-400/80",children:"Data modified — recapture to update the screenshot"}),n("div",{className:"flex-1"}),n("button",{onClick:()=>{M(!0),Promise.resolve().then(()=>(s&&s(),new Promise(A=>setTimeout(A,2e3)))).then(()=>fetch("/api/editor-capture-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e})})).then(()=>_(!1)).catch(()=>{}).finally(()=>M(!1))},disabled:$,className:"px-3 py-1 text-[10px] font-medium text-white bg-amber-600 rounded cursor-pointer border-none hover:bg-amber-500 disabled:opacity-50 transition-colors",children:$?"Recapturing...":"Recapture Screenshot"})]}),r&&d("div",{className:"border-t border-[#3d3d3d]",children:[n("div",{className:"flex justify-center py-2",children:n("button",{onClick:()=>g(!y),className:"px-3 py-1 text-[10px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:y?"Hide Claude":"Edit with Claude"})}),y&&n("div",{className:"border-t border-[#3d3d3d]",children:n(qt,{prompt:r,height:400,onClose:()=>{g(!1),k(A=>A+1)}})})]})]});function j(){if(R.current&&clearTimeout(R.current),!!x){if(v!==w){if(o&&m){const A=o[m];if(A&&A[x.row]){let L=w;w===""?L="":w==="null"?L=null:w==="true"?L=!0:w==="false"?L=!1:isNaN(Number(w))||(L=Number(w));const E=[...A];E[x.row]={...E[x.row],[x.col]:L},a({...o,[m]:E})}}fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:z.dataKey,rowIndex:x.row,column:x.col,value:w})}).then(()=>{s&&s()}).catch(()=>{})}b(null),_(!1)}}async function D(A,L,E,F){if(o&&m){const I=o[m];if(I&&I[L]){let K=F;F==="null"?K=null:F==="true"?K=!0:F==="false"?K=!1:F!==""&&!isNaN(Number(F))&&(K=Number(F));const Q=[...I];Q[L]={...Q[L],[E]:K},a({...o,[m]:Q})}}_(!0);try{await fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:A,rowIndex:L,column:E,value:F})}),s&&s()}catch{}}}function y5(){const[e,t]=P([]),[r,s]=P([]),[o,a]=P(!0),[i,l]=P(null),[c,u]=P(!1),[p,h]=P(null);if(se(()=>{fetch("/api/editor-schema").then(g=>g.json()).then(g=>{var x,b;h(g.source||null),g.source==="explicit"?(s(g.dataStructures||[]),((x=g.dataStructures)==null?void 0:x.length)>0&&l(g.dataStructures[0].name)):(t(g.models||[]),((b=g.models)==null?void 0:b.length)>0&&l(g.models[0].name))}).catch(()=>{}).finally(()=>a(!1))},[]),o)return n("div",{className:"text-xs text-gray-400 py-4",children:"Loading schema..."});if(!(p==="explicit"?r.length>0:e.length>0))return n("div",{className:"text-xs text-gray-500 py-4",children:"No data structure found. Use the chat below to have Claude analyze your codebase and generate one."});const f=p==="explicit"?v5(r):b5(e,p);return p==="explicit"?d("div",{className:"space-y-2",children:[r.map(g=>{const x=i===g.name,b=g.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30":g.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border border-blue-400/30":"text-gray-400 bg-gray-700/30 border border-gray-600/30";return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform shrink-0 ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),g.order===1&&n("span",{className:"text-[9px] text-amber-400/70",children:"Primary"}),n("span",{className:`text-[9px] rounded px-1.5 py-0 ${b}`,children:g.category==="mock-api"?"API Mock":g.category}),d("span",{className:"text-[10px] text-gray-500",children:[g.fields.length," fields"]})]}),x&&d("div",{className:"border-t border-[#3d3d3d]",children:[g.description&&n("div",{className:"px-3 py-1.5 text-[10px] text-gray-400 border-b border-[#2d2d2d]",children:g.description}),n("table",{className:"w-full text-[10px]",children:n("tbody",{children:g.fields.map(v=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[v.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),v.name]}),n("td",{className:"px-3 py-1.5 text-gray-500",children:v.type}),n("td",{className:"px-3 py-1.5 text-gray-600 w-16 text-right",children:v.required===!1?"optional":""})]},v.name))})})]})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>u(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:f,height:500,onClose:()=>u(!1)})})]}):d("div",{className:"space-y-2",children:[n(x5,{prompt:`Analyze this codebase and generate a .codeyam/data-structure.json file that describes the app's data structures.
|
|
618
|
+
|
|
619
|
+
The file should be a JSON array where each entry has:
|
|
620
|
+
- "name": display name for the data structure
|
|
621
|
+
- "description": what this data represents and how it's used
|
|
622
|
+
- "category": either "datastore" (persisted data like DB tables, localStorage) or "mock-api" (mocked external API responses)
|
|
623
|
+
- "order": integer for display order (1 = primary/most important)
|
|
624
|
+
- "fields": array of { "name", "type", "isId" (boolean), "required" (boolean) }
|
|
625
|
+
|
|
626
|
+
Look at:
|
|
627
|
+
- Database schemas (prisma/schema.prisma, SQLite, etc.)
|
|
628
|
+
- TypeScript interfaces/types used for stored data
|
|
629
|
+
- localStorage usage patterns
|
|
630
|
+
- API response types that need mocking
|
|
631
|
+
- Do NOT include types that are only used as component props
|
|
632
|
+
|
|
633
|
+
Write the file to .codeyam/data-structure.json.`}),e.map(g=>{const x=i===g.name,b=g.fields.filter(N=>N.isRelation),v=g.fields.filter(N=>!N.isRelation);return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),d("span",{className:"text-[10px] text-gray-500",children:[v.length," fields"]}),b.length>0&&d("span",{className:"text-[10px] text-[#D7FF63]/70",children:[b.length," relation",b.length>1?"s":""]})]}),x&&n("div",{className:"border-t border-[#3d3d3d]",children:n("table",{className:"w-full text-[10px]",children:d("tbody",{children:[v.map(N=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[N.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),N.name]}),d("td",{className:"px-3 py-1.5 text-gray-500",children:[N.type,N.isOptional&&"?",N.isList&&"[]"]})]},N.name)),b.length>0&&n("tr",{children:d("td",{colSpan:2,className:"px-3 py-1.5 border-t border-[#3d3d3d]",children:[n("span",{className:"text-[9px] text-gray-500 uppercase tracking-wider",children:"Relations"}),n("div",{className:"mt-1 flex flex-wrap gap-1.5",children:b.map(N=>n("button",{onClick:()=>l(N.relatedModel??null),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors",children:N.isList?`${N.relatedModel}[]`:N.relatedModel},N.name))})]})})]})})})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>u(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:f,height:500,onClose:()=>u(!1)})})]})}function x5({prompt:e}){const[t,r]=P(!1),[s,o]=P(()=>typeof window>"u"?!1:localStorage.getItem("codeyam-ds-migration-dismissed")==="1");return s?null:d("div",{className:"relative border border-amber-500/30 bg-amber-500/5 rounded-lg p-3 pr-8",children:[n("button",{onClick:()=>{o(!0),localStorage.setItem("codeyam-ds-migration-dismissed","1")},className:"absolute top-2 right-2 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-[11px] text-amber-400/90 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:"This data structure was auto-detected. For better results, ask Claude to generate an explicit data structure config."}),n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"mt-2 px-3 py-1 text-[10px] font-medium text-amber-400 border border-amber-500/40 rounded cursor-pointer transition-colors hover:bg-amber-500/10 bg-transparent",children:t?"Copied!":"Copy prompt for Claude"})]})}function b5(e,t){const r=e.map(o=>{const a=o.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isList&&(l+="[]"),i.isOptional&&(l+=" (optional)"),i.isId&&(l+=" [PK]"),i.isRelation&&(l+=` → ${i.relatedModel}`),l}).join(`
|
|
634
|
+
`);return`${o.name}:
|
|
635
|
+
${a}`}).join(`
|
|
636
|
+
|
|
637
|
+
`);return`You are helping the user understand and modify the data structure of their application.
|
|
638
|
+
|
|
639
|
+
${t==="prisma"?"The data structure is defined in `prisma/schema.prisma`.":t==="typescript"?"The data structure is defined via TypeScript interfaces in the `src/` directory.":"The data structure was inferred from the project."}
|
|
640
|
+
|
|
641
|
+
Here is the current data structure:
|
|
642
|
+
|
|
643
|
+
${r}
|
|
644
|
+
|
|
645
|
+
Wait for the user to tell you what they want to do. They might want to:
|
|
646
|
+
- Add new models/tables
|
|
647
|
+
- Add or modify fields on existing models
|
|
648
|
+
- Understand relationships between models
|
|
649
|
+
- Get advice on data modeling
|
|
650
|
+
- Generate or modify seed data for scenarios
|
|
651
|
+
|
|
652
|
+
When making changes:
|
|
653
|
+
${t==="prisma"?"- Edit `prisma/schema.prisma` directly":"- Edit the TypeScript interface files in `src/`"}
|
|
654
|
+
- After schema changes, update any affected scenario seed data
|
|
655
|
+
- Explain the impact of changes on existing data
|
|
656
|
+
|
|
657
|
+
Do NOT start making changes until the user tells you what they want.`}function v5(e){return`You are helping the user understand and modify the data structure of their application.
|
|
658
|
+
|
|
659
|
+
The data structure is explicitly defined in \`.codeyam/data-structure.json\`.
|
|
660
|
+
|
|
661
|
+
Here is the current data structure:
|
|
662
|
+
|
|
663
|
+
${e.map(r=>{const s=r.category==="datastore"?"[datastore]":r.category==="mock-api"?"[mock-api]":`[${r.category}]`,o=r.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isId&&(l+=" [PK]"),i.required===!1&&(l+=" (optional)"),l}).join(`
|
|
664
|
+
`),a=r.description?` ${r.description}`:"";return`${r.name} ${s}${a?`
|
|
665
|
+
${a}`:""}
|
|
666
|
+
${o}`}).join(`
|
|
667
|
+
|
|
668
|
+
`)}
|
|
669
|
+
|
|
670
|
+
Each data structure has:
|
|
671
|
+
- **name**: display name
|
|
672
|
+
- **description**: what this data represents
|
|
673
|
+
- **category**: "datastore" (persisted data) or "mock-api" (mocked external API)
|
|
674
|
+
- **order**: display order (1 = primary)
|
|
675
|
+
- **fields**: array of { name, type, isId, required }
|
|
676
|
+
|
|
677
|
+
Wait for the user to tell you what they want to do. They might want to:
|
|
678
|
+
- Add new data structures (tables, API mocks)
|
|
679
|
+
- Add or modify fields
|
|
680
|
+
- Change categories or descriptions
|
|
681
|
+
- Understand how data flows through the app
|
|
682
|
+
|
|
683
|
+
When making changes:
|
|
684
|
+
- Edit \`.codeyam/data-structure.json\` directly
|
|
685
|
+
- Keep the file as a JSON array sorted by order
|
|
686
|
+
- Update descriptions to reflect changes
|
|
687
|
+
- After data structure changes, update affected scenario seed data
|
|
688
|
+
|
|
689
|
+
Do NOT start making changes until the user tells you what they want.`}function cd({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function w5({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:o,runTests:a,stale:i}=tl(e,r);if(o&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const u=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-400":p.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:f,children:f.split(`
|
|
690
|
+
`)[0]},y)))]},p.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:a,disabled:o,className:"text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:o?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!o&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}const N5={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function S5({files:e}){return d("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[d("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",e.length,")"]}),n("div",{className:"mt-1 space-y-0.5 max-h-[150px] overflow-auto",children:e.map(t=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${N5[t.status]||"text-gray-500"}`,children:t.status==="added"||t.status==="untracked"?"A":t.status==="modified"?"M":t.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-400 truncate font-mono",children:t.path})]},t.path))})]})}const C5={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function k5(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function E5(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const _5=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function j5({entries:e,onScreenshotClick:t}){const[r,s]=P(!1),[o,a]=P("7d"),i=pe(()=>vw(e,o),[e,o]);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>s(!r),className:"w-full flex items-center justify-between px-3 py-2.5 cursor-pointer bg-transparent border-none text-left hover:bg-[#333] transition-colors",children:[n("span",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Timeframe Summary"}),n("span",{className:`text-gray-500 text-[10px] transition-transform ${r?"rotate-180":""}`,children:"▼"})]}),r&&d("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:_5.map(l=>n("button",{onClick:()=>a(l.value),className:`px-2.5 py-1 text-[10px] font-medium rounded transition-colors cursor-pointer border ${o===l.value?"bg-[#005c75] text-white border-[#005c75]":"bg-transparent text-gray-400 border-[#4d4d4d] hover:text-white hover:border-[#005c75]"}`,children:l.label},l.value))}),d("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[d("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.totalScenarios})," ",i.totalScenarios===1?"scenario changed":"scenarios changed"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.entryCount})," ",i.entryCount===1?"entry":"entries"]})]}),i.totalScenarios===0?n("p",{className:"text-[11px] text-gray-500 italic m-0",children:"No scenario changes in this period."}):d("div",{className:"space-y-3",children:[i.appScenarios.length>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),i.appScenarios.map(l=>n(dd,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(u=>n(dd,{scenario:u,onScreenshotClick:t},u.name))]},l))]})]})]})]})}function dd({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return d("div",{className:"pl-2",children:[n("span",{className:"text-[10px] text-gray-500 block mb-1",children:s}),n("div",{className:"flex items-center gap-1 overflow-x-auto",children:e.screenshots.map((o,a)=>d("div",{className:"flex items-center shrink-0",children:[a>0&&n("span",{className:"text-[8px] text-gray-600 mx-0.5",children:"→"}),n("button",{type:"button",className:"w-16 h-16 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",title:`${e.name} (${new Date(o.time).toLocaleDateString()})`,onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${o.path.replace("screenshots/","")}`,commitSha:null,commitMessage:null,scenarioName:e.name}),children:n("img",{src:`/api/editor-journal-image/${o.path.replace("screenshots/","")}`,alt:e.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})})]},o.path))})]})}function P5({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],cachedTestResults:s={}}){const[o,a]=P([]),[i,l]=P(!0),[c,u]=P(new Set),p=ce(f=>{u(y=>{const g=new Set(y);return g.has(f)?g.delete(f):g.add(f),g})},[]),h=ce(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const y=await f.json();a(y.entries||[])}}catch{}finally{l(!1)}},[]);if(se(()=>{h()},[h]),se(()=>{e&&h()},[e,h]),se(()=>{if(!e)return;const f=setInterval(()=>void h(),5e3);return()=>clearInterval(f)},[e,h]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(o.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const m=ww(o);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(j5,{entries:o,onScreenshotClick:t}),[...m.entries()].map(([f,y])=>d("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:E5(f)})}),n("div",{className:"space-y-2",children:y.map((g,x)=>{const b=C5[g.type]||{label:g.type,color:"bg-gray-600"},v=`${g.time}-${x}`,N=c.has(v);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${N?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>p(v),children:d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:g.title}),n("span",{className:`${b.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:b.label})]}),n("span",{className:"text-[10px] text-gray-500",children:k5(g.time)}),g.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:g.featureName,children:g.featureName})]})}),g.userPrompt&&n(Vp,{text:g.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:g.description}),g.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:g.title}),children:n("img",{src:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,alt:g.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),g.scenarioScreenshots&&g.scenarioScreenshots.length>0&&(()=>{const w=Nw(g.scenarioScreenshots),C=g.entityChangeStatus,S=w.filter(([M])=>M==="App").flatMap(([,M])=>M),k=w.filter(([M])=>M!=="App"),T=new Map;for(const M of S){const R=M,z=R.pageFilePath?Ut($t(R.pageFilePath)):Ct(R.url??null),O=T.get(z)||[];O.push(M),T.set(z,O)}const _=[...T.entries()],$=M=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${M.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:M.name}),children:n("img",{src:`/api/editor-journal-image/${M.path.replace("screenshots/","")}`,alt:M.name,title:M.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},M.path);return d("div",{className:"space-y-2",children:[_.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),_.map(([M,R])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:M}),(C==null?void 0:C[M])&&n(cd,{status:C[M]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:R.map($)})]},M))]}),k.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),k.map(([M,R])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:M}),(C==null?void 0:C[M])&&n(cd,{status:C[M]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:R.map($)})]},M))]})]})})(),r.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(w=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:w.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:w.filePath}),w.testFile?n(w5,{testFile:w.testFile,entityName:w.name,cachedResult:s[w.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.name))})]}),g.commitSha&&d("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:g.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:g.commitMessage})]}),N&&g.modifiedFiles&&g.modifiedFiles.length>0&&n(S5,{files:g.modifiedFiles})]}),d("button",{onClick:()=>p(v),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",N?"Collapse":"Expand"," ———"]})]},v)})})]},f))]})})}const A5=()=>n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})});function Ca({title:e,completedCount:t,totalCount:r,subtitle:s,onClick:o,secondaryAction:a,previewTasks:i}){const l=r>0&&t>=r;return d("button",{type:"button",onClick:o,className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-3 flex flex-col gap-1.5 cursor-pointer hover:border-[#555] transition-colors text-left",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white",children:e}),l?n(A5,{}):r>0?d("span",{className:"text-xs text-gray-500",children:["(",t,"/",r,")"]}):null]}),s&&n("p",{className:"text-xs text-gray-400 m-0 leading-snug",children:s}),i&&i.length>0&&n("div",{className:"flex flex-col gap-1 mt-0.5",children:i.map(c=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[11px] truncate flex-1 ${c.completed?"text-gray-300":"text-gray-500"}`,children:c.label}),c.completed?n("span",{className:"shrink-0 w-3.5 h-3.5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 text-[9px] font-medium text-amber-400 bg-amber-400/15 px-1 py-px rounded",children:"pending"})]},c.label))}),a&&n("span",{role:"link",onClick:c=>{c.stopPropagation(),a.onClick()},className:"text-xs text-[#D7FF63]/70 hover:text-[#D7FF63] text-left truncate mt-0.5",children:a.label})]})}function T5({onNavigateToRoadmap:e,onSwitchToBuild:t}){const[r,s]=P(null),o=ce(()=>{fetch("/api/editor-roadmap").then(m=>m.json()).then(m=>s(m)).catch(()=>{})},[]);if(se(()=>{o()},[o]),!r)return null;const a=r.plan.filter(m=>m.completed).length,i=r.plan.length,l=r.deploy.filter(m=>m.completed).length,c=r.deploy.length,u=r.buildSessionCount===1?"1 working session":`${r.buildSessionCount} working sessions`,p=r.featureName&&r.editorStepLabel?`${r.featureName} — ${r.editorStepLabel}`:r.featureName?r.featureName:null,h=m=>{const f=[...m].reverse().find(g=>g.completed),y=m.filter(g=>!g.completed);if(f){const g=[{label:f.label,completed:!0}];return y.length>0&&g.push({label:y[0].label,completed:!1}),g}return y.slice(0,2).map(g=>({label:g.label,completed:!1}))};return d("div",{children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider font-['IBM_Plex_Mono']",children:"Roadmap"}),d("div",{className:"grid grid-cols-3 gap-3 mt-2",children:[n(Ca,{title:"Plan",completedCount:a,totalCount:i,onClick:e,previewTasks:h(r.plan)}),n(Ca,{title:"Build",completedCount:r.buildSessionCount,totalCount:0,subtitle:u,onClick:e,secondaryAction:p?{label:p,onClick:t}:{label:"No work is in progress. Start the next working session >",onClick:t}}),n(Ca,{title:"Deploy",completedCount:l,totalCount:c,onClick:e,previewTasks:h(r.deploy)})]})]})}function Ka(e){return{name:M5(e),description:$5(e),colors:F5(e),fonts:R5(e),typographyScale:D5(e),radiusTokens:I5(e)}}function M5(e){const t=e.match(/^# (.+)$/m);return t?t[1].trim():"Design System"}function $5(e){const t=e.match(/^> (.+)$/m);return t?t[1].trim():""}function F5(e){const t=[],r=rl(e,"Colors");if(!r)return t;const s=z5(r);for(const{heading:o,content:a}of s){const i=Qp(a);for(const l of i){const c=/--([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let u;for(;(u=c.exec(l))!==null;){const p=u[2].trim();B5(p)&&t.push({name:u[1],value:p,group:o,...u[3]?{comment:u[3]}:{}})}}}return t}function R5(e){const t=e.match(/\*\*Font stack:\*\*\s*`([^`]+)`(?:\s*\([^)]*\))?(?:,\s*`([^`]+)`)?/);if(!t)return[];const r=[];if(t[1]){const o=ka(t[1]);o&&r.push(o)}if(t[2]){const o=ka(t[2]);o&&!r.includes(o)&&r.push(o)}const s=e.match(/\*\*Font stack:\*\*\s*`[^`]+`[^`]*`[^`]+`[^`]*`([^`]+)`/);if(s){const o=ka(s[1]);o&&!r.includes(o)&&r.push(o)}return r}function ka(e){return e.split(",")[0].trim().replace(/'/g,"")||null}function D5(e){const t=[],r=rl(e,"Typography");if(!r)return t;const s=r.split(`
|
|
691
|
+
`).filter(o=>o.startsWith("|"));if(s.length<3)return t;for(let o=2;o<s.length;o++){const a=s[o].split("|").map(i=>i.trim()).filter(Boolean);a.length>=3&&t.push({style:a[0],size:a[1],weight:a[2],notes:a.slice(3).join(" | ")})}return t}function I5(e){const t=[],r=rl(e,"Spacing");if(!r)return t;const s=Qp(r);for(const o of s){const a=/--radius-([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let i;for(;(i=a.exec(o))!==null;)t.push({name:`radius-${i[1]}`,value:i[2].trim(),...i[3]?{comment:i[3]}:{}})}return t}function O5(e,t,r){const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(--${s}:\\s*)([^;]+)(;.*)`,"g");return e.replace(o,`$1${r}$3`)}function L5(e,t){return e.replace(/(\*\*Font stack:\*\*\s*`)([^`]+)(`)/,`$1${t}$3`)}function rl(e,t){const s=new RegExp(`^## .*${t}.*$`,"im").exec(e);if(!s)return null;const o=s.index+s[0].length,a=e.indexOf(`
|
|
692
|
+
## `,o);return a===-1?e.slice(o):e.slice(o,a)}function z5(e){const t=[],r=e.split(/^### /m);for(let s=0;s<r.length;s++){if(s===0){const a=r[s].trim();a&&t.push({heading:"General",content:a});continue}const o=r[s].indexOf(`
|
|
693
|
+
`);o===-1?t.push({heading:r[s].trim(),content:""}):t.push({heading:r[s].slice(0,o).trim(),content:r[s].slice(o+1)})}return t}function Qp(e){const t=[],r=/```css\n([\s\S]*?)```/g;let s;for(;(s=r.exec(e))!==null;)t.push(s[1]);return t}function B5(e){return!!(e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("var(--"))}const ud=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function pd({todo:e,expanded:t,onToggle:r,onRemove:s,children:o}){return d("div",{children:[d("div",{className:"flex items-center gap-2 py-1.5 group cursor-pointer",onClick:r,children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-gray-500 transition-transform ${t?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),d("span",{className:`text-sm flex-1 ${e.completed?"text-white":"text-gray-500"}`,children:[e.label,e.autoDetect&&!e.userCreated&&n("span",{className:"text-[10px] text-gray-600 ml-1.5",children:"(auto)"})]}),e.completed?n("span",{className:"shrink-0 w-5 h-5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 text-[10px] font-medium text-amber-400 bg-amber-400/15 px-1.5 py-0.5 rounded",children:"pending"}),e.userCreated&&s&&n("button",{type:"button",onClick:a=>{a.stopPropagation(),s()},className:"opacity-0 group-hover:opacity-100 text-gray-600 hover:text-red-400 bg-transparent border-none cursor-pointer p-0 transition-opacity",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})})]}),t&&o]})}function hd({title:e,completedCount:t,totalCount:r}){const s=r>0&&t>=r;return d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-sm font-medium text-white m-0",children:e}),s?n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})}):r>0?d("span",{className:"text-xs text-gray-500",children:[t,"/",r]}):null]})}const Y5={feature:"bg-[#005c75]",fix:"bg-amber-700",refactor:"bg-purple-700",scaffold:"bg-green-700",data:"bg-blue-700",milestone:"bg-yellow-600"};function U5(e){try{return new Date(e).toLocaleDateString([],{month:"short",day:"numeric"})}catch{return""}}function W5({designSystem:e,onEdit:t}){const r=e.colors.filter(s=>s.value.startsWith("#")).slice(0,10);return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs font-medium text-gray-200 mb-2",children:e.name}),r.length>0&&n("div",{className:"flex gap-1.5 mb-2 flex-wrap",children:r.map(s=>n("div",{className:"w-5 h-5 rounded border border-[#444]",style:{backgroundColor:s.value},title:`--${s.name}: ${s.value}`},`${s.group}-${s.name}`))}),e.fonts.length>0&&d("div",{className:"text-[10px] text-gray-500 mb-2",children:["Font: ",e.fonts.join(", ")]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"View & Edit >"})]})}function md({projectTitle:e,projectDescription:t,onSave:r,onEditNavigate:s,defaultEditing:o=!1}){const[a,i]=P(o),[l,c]=P(e||""),[u,p]=P(t||""),[h,m]=P(!1);se(()=>{c(e||""),p(t||"")},[e,t]);const f=()=>{m(!0),r(l,u),m(!1),i(!1)},y=()=>{c(e||""),p(t||""),i(!1)};return a?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:d("div",{className:"space-y-2.5",children:[d("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Project Name"}),n("input",{type:"text",value:l,onChange:g=>c(g.target.value),placeholder:"My App",className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"})]}),d("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Description"}),n("textarea",{value:u,onChange:g=>p(g.target.value),placeholder:"A brief description of your project...",rows:2,className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors resize-none"})]}),d("div",{className:"flex gap-2 pt-0.5",children:[n("button",{type:"button",onClick:f,disabled:h,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium disabled:opacity-50",children:h?"Saving...":"Save"}),n("button",{type:"button",onClick:y,className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}):d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[e?n("div",{className:"text-xs font-medium text-gray-200 mb-0.5",children:e}):n("div",{className:"text-xs text-gray-500 italic mb-0.5",children:"No name set"}),t&&n("div",{className:"text-[11px] text-gray-400 leading-relaxed",children:t}),n("button",{type:"button",onClick:s??(()=>i(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}function J5({techStack:e,onNavigate:t}){if(!(e&&ud.some(({key:i})=>e[i]&&e[i].length>0)))return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-400 mb-2",children:"No tech stack configured yet"}),t&&n("button",{type:"button",onClick:t,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude >"})]});const s=[];for(const{key:i}of ud){const l=e[i];if(l)for(const c of l)s.push(c)}const o=s.slice(0,5),a=s.length-5;return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[d("div",{className:"flex flex-wrap gap-1.5",children:[o.map((i,l)=>d("span",{className:"inline-flex items-center gap-1 text-xs text-gray-300 bg-[#2a2a2a] px-2 py-0.5 rounded",children:[i.name,i.version&&d("span",{className:"text-[10px] text-gray-500",children:["v",i.version]})]},l)),a>0&&d("span",{className:"text-[10px] text-gray-500 self-center",children:["+",a," more"]})]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"View all >"})]})}function Ea({iconType:e,size:t=14,className:r=""}){const s={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(e){case"desktop":return d("svg",{...s,children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]});case"laptop":return d("svg",{...s,children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]});case"tablet":return d("svg",{...s,children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]});case"mobile":return d("svg",{...s,children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})}}function fd({open:e,size:t=12}){return e?d("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}):d("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),n("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),n("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}const H5=new Set(Yp.flatMap(e=>e.presets.map(t=>t.name)));function gd({screenSizes:e,projectScreenSizes:t,defaultScreenSize:r,appFormats:s,onSave:o,onEditNavigate:a,defaultEditing:i=!1}){const l=pe(()=>Up(e,s),[e,s]),c=pe(()=>{if(e){for(const[W,J]of Object.entries(e))if(J.default)return W}return(r==null?void 0:r.name)||""},[e,r]),[u,p]=P(i),[h,m]=P({}),[f,y]=P(new Set),[g,x]=P(""),[b,v]=P(""),[N,w]=P(""),[C,S]=P(""),k=()=>{const W={};for(const D of l)W[D.name]={width:D.width,height:D.height};m(W);const J=new Set,j=t||e;if(j)for(const D of Object.keys(j)){const A=j[D];(t||!A||!("default"in A))&&J.add(D)}y(J),x(c),v(""),w(""),S(""),p(!0)};se(()=>{i&&k()},[]);const T=(W,J,j)=>{m(D=>{const A={...D};if(A[W]){if(delete A[W],y(L=>{const E=new Set(L);return E.delete(W),E}),W===g){const L=Object.keys(A);x(L[0]||"")}}else A[W]={width:J,height:j},Object.keys(D).length===0&&x(W);return A})},_=W=>{y(J=>{const j=new Set(J);return j.has(W)?j.delete(W):j.add(W),j})},$=W=>{h[W]&&x(W)},M=()=>{const W=b.trim(),J=parseInt(N,10),j=parseInt(C,10);!W||isNaN(J)||isNaN(j)||J<=0||j<=0||(m(D=>(Object.keys(D).length===0&&x(W),{...D,[W]:{width:J,height:j}})),v(""),w(""),S(""))},R=W=>{m(J=>{const j={...J};return delete j[W],W===g&&x(Object.keys(j)[0]||""),j}),y(J=>{const j=new Set(J);return j.delete(W),j})},z=()=>{const W={};for(const[j,D]of Object.entries(h))W[j]={width:D.width,height:D.height,...j===g?{default:!0}:{}};const J={};for(const j of f)h[j]&&(J[j]={...h[j]});o(W,J),p(!1)};if(u){const W=Object.entries(h).filter(([J])=>!H5.has(J));return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[d("div",{className:"flex items-center gap-2 mb-2 px-0.5",children:[n("div",{className:"w-3.5"}),n("div",{className:"w-3.5"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider flex-1",children:"Size"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[72px] text-right",children:"Dimensions"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[50px] text-center",title:"Include in project screenshot sizes",children:"Project"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[54px] text-center",children:"Default"})]}),d("div",{className:"space-y-3",children:[Yp.map(J=>d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:J.category}),n("div",{className:"space-y-0.5",children:J.presets.map(j=>{const D=!!h[j.name],A=g===j.name,L=f.has(j.name),E=Ys(j);return d("div",{className:"flex items-center gap-2 py-0.5",children:[n("button",{type:"button",onClick:()=>T(j.name,j.width,j.height),className:`w-3.5 h-3.5 rounded-sm border flex items-center justify-center shrink-0 cursor-pointer transition-colors ${D?"bg-[#D7FF63] border-[#D7FF63]":"bg-transparent border-[#555] hover:border-[#888]"}`,children:D&&n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#1e1e1e",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}),n(Ea,{iconType:E,size:14,className:D?"text-gray-300":"text-gray-600"}),n("span",{className:`text-xs flex-1 ${D?"text-gray-300":"text-gray-500"}`,children:j.name}),d("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[j.width," × ",j.height]}),n("div",{className:"w-[50px] flex justify-center",children:D?n("button",{type:"button",onClick:()=>_(j.name),className:`p-1 rounded cursor-pointer transition-colors ${L?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:L?"In project screenshots":"Not in project screenshots",children:n(fd,{open:L})}):n("span",{className:"w-3"})}),n("div",{className:"w-[54px] flex justify-center",children:D?n("button",{type:"button",onClick:()=>$(j.name),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${A?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:A?"Default size":"Set as default",children:A?"★":"☆"}):n("span",{className:"w-3"})})]},j.name)})})]},J.category)),W.length>0&&d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Custom"}),n("div",{className:"space-y-0.5",children:W.map(([J,j])=>{const D=g===J,A=f.has(J),L=Ys({name:J,width:j.width,height:j.height});return d("div",{className:"flex items-center gap-2 py-0.5",children:[n("div",{className:"w-3.5"}),n(Ea,{iconType:L,size:14,className:"text-gray-300"}),n("span",{className:"text-xs text-gray-300 flex-1",children:J}),d("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[j.width," × ",j.height]}),n("div",{className:"w-[50px] flex justify-center",children:n("button",{type:"button",onClick:()=>_(J),className:`p-1 rounded cursor-pointer transition-colors ${A?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:A?"In project screenshots":"Not in project screenshots",children:n(fd,{open:A})})}),n("div",{className:"w-[54px] flex justify-center",children:n("button",{type:"button",onClick:()=>$(J),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${D?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:D?"Default size":"Set as default",children:D?"★":"☆"})}),n("button",{type:"button",onClick:()=>R(J),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]},J)})})]}),d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Add Custom Size"}),d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:b,onChange:J=>v(J.target.value),placeholder:"Name",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"number",value:N,onChange:J=>w(J.target.value),placeholder:"W",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("span",{className:"text-[10px] text-gray-500",children:"×"}),n("input",{type:"number",value:C,onChange:J=>S(J.target.value),placeholder:"H",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:M,className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"+ Add"})]})]})]}),d("div",{className:"flex gap-2 pt-2.5",children:[n("button",{type:"button",onClick:z,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>p(!1),className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}if(l.length===0)return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-500 italic",children:"No screen sizes configured"}),n("button",{type:"button",onClick:a??k,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]});const O=W=>c===W,U=W=>{var J;return!!((J=t||e)!=null&&J[W])};return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"flex flex-wrap gap-1.5",children:l.map(W=>{const J=Ys(W);return d("span",{className:"inline-flex items-center gap-1.5 text-xs bg-[#2a2a2a] px-2 py-1 rounded text-gray-300",children:[n(Ea,{iconType:J,size:12,className:"text-gray-400"}),W.name,d("span",{className:"text-[10px] text-gray-500",children:[W.width,"×",W.height]}),O(W.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",children:"★"}),U(W.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",title:"Project screenshot size",children:"P"})]},W.name)})}),n("button",{type:"button",onClick:a??k,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}const yd=[{id:"vercel",name:"Vercel",services:["Hosting"],description:"Frontend-optimized hosting"},{id:"railway",name:"Railway",services:["Hosting","Database","Storage"],description:"Full-stack infrastructure"},{id:"runloop",name:"Runloop",services:["Sandboxes","Hosting"],description:"Sandbox-first deployment"}];function sr({step:e,done:t,active:r}){return n("span",{className:`shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold ${t?"bg-green-600 text-white":r?"bg-[#D7FF63] text-black":"bg-[#333] text-gray-500"}`,children:t?n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})}):e})}function V5({hosting:e,onSave:t}){var oe;const[r,s]=P(null),[o,a]=P(!0),[i,l]=P(""),[c,u]=P(!1),[p,h]=P([]),[m,f]=P(null),[y,g]=P(!1),[x,b]=P(!1),[v,N]=P(!1),[w,C]=P(!1),[S,k]=P(null),[T,_]=P(null),[$,M]=P(null),[R,z]=P(null),[O,U]=P(null),W=ce(()=>{a(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"full-status"})}).then(Z=>Z.json()).then(Z=>{s(Z),M(null)}).catch(()=>M("Failed to check status")).finally(()=>a(!1))},[]);se(()=>{W()},[W]);const J=()=>{i.trim()&&(u(!0),M(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"save-token",token:i.trim()})}).then(Z=>Z.json()).then(Z=>{Z.ok?(l(""),W()):M(Z.error||"Token verification failed")}).catch(()=>M("Failed to save token")).finally(()=>u(!1)))},[j,D]=P(!1),A=ce(()=>{g(!0),M(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"list-projects"})}).then(Z=>Z.json()).then(Z=>{Z.ok?(h(Z.projects||[]),f(Z.suggestedProjectId||null),_(Z.gitHubRepo||null)):M(Z.error||"Failed to load projects"),D(!0)}).catch(Z=>{M(`Failed to load projects: ${Z.message||"network error"}`),D(!0)}).finally(()=>g(!1))},[]),L=()=>{N(!0),M(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"create-project"})}).then(Z=>Z.json()).then(Z=>{Z.ok?(t({provider:"vercel",vercelProjectId:Z.project.id,vercelProjectName:Z.project.name}),W()):M(Z.error||"Failed to create project")}).catch(()=>M("Failed to create project")).finally(()=>N(!1))},E=(Z,re)=>{b(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"link-project",projectId:Z,projectName:re})}).then(ue=>ue.json()).then(ue=>{ue.ok&&(t({provider:"vercel",vercelProjectId:Z,vercelProjectName:re}),W())}).catch(()=>{}).finally(()=>b(!1))},F=r||{hasToken:!1,tokenVerified:!1,user:null,projectLinked:!1,projectName:null,dashboardUrl:null,productionUrl:null,lastDeployment:null,envVarsChecked:!1,envVars:[]},I=F.tokenVerified,K=F.projectLinked,Q=F.envVars.filter(Z=>Z.configuredOnVercel).length,V=F.envVars.length,Y=F.envVarsChecked&&(V===0||Q===V),B=I?K?3:2:1,H=ce(Z=>{var we;const re=[`Step 1 (Account & Token): ${F.tokenVerified?`Connected as ${(we=F.user)==null?void 0:we.username}`:F.hasToken?"Token found but verification failed":"Not started"}`,`Step 2 (Link Project): ${F.projectLinked?`Linked to "${F.projectName}"`:"Not linked"}`,`Step 3 (Environment Variables): ${F.envVarsChecked?F.envVars.length===0?"No env vars needed":`${F.envVars.filter(je=>je.configuredOnVercel).length}/${F.envVars.length} configured`:"Not checked yet"}`];F.lastDeployment&&re.push(`Last deployment: ${F.lastDeployment.state} (${F.lastDeployment.commitsSince} commits since)`);const ue=["# Vercel Setup Help","","The user is setting up Vercel hosting for their project and needs help.","","## Current Status",...re.map(je=>`- ${je}`),$?`
|
|
694
|
+
## Current Error
|
|
695
|
+
\`\`\`
|
|
696
|
+
${$}
|
|
697
|
+
\`\`\``:"",Z?`
|
|
698
|
+
## Additional Context
|
|
699
|
+
${Z}`:"","","## What You Can Do","- Help the user understand what they need to do next","- If there is a deployment error, help them debug it","- You can read project files to understand the setup (package.json, next.config.ts, etc.)","- Guide them to the right Vercel documentation or settings pages","- If the issue is about GitHub permissions, guide them to vercel.com/account/login-connections","","Start by acknowledging what step they are on and ask what they need help with."].filter(Boolean).join(`
|
|
700
|
+
`);z(ue),Promise.resolve().then(()=>UC).then(je=>{U(()=>je.MiniClaudeChat)})},[F,$]),ne=ye(!1);return se(()=>{B===2&&!ne.current&&p.length===0&&!y&&(ne.current=!0,A())},[B,p.length,y,A]),se(()=>{if(!S)return;const Z=["READY","ERROR","CANCELED"];if(Z.includes(S.state))return;const re=setInterval(()=>{fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"check-deployment",deploymentId:S.id})}).then(ue=>ue.json()).then(ue=>{ue.ok&&(k(we=>we?{...we,state:ue.state,url:ue.url||we.url,errorMessage:ue.errorMessage,logsUrl:ue.logsUrl}:null),Z.includes(ue.state)&&W())}).catch(()=>{})},5e3);return()=>clearInterval(re)},[S,W]),o&&!r?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:n("span",{className:"text-xs text-gray-500",children:"Checking Vercel setup..."})}):d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333] space-y-3",children:[d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Vercel Setup"}),n("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:"Vercel deploys your app to the web. Push your code and Vercel automatically builds and hosts it at a public URL — no server setup required. Free for personal projects."})]}),$&&d("div",{className:"text-[11px] bg-red-400/10 rounded px-2.5 py-2 space-y-1.5",children:[n("p",{className:"text-red-400 m-0",children:$}),$.toLowerCase().includes("login connection")&&d(ve,{children:[n("p",{className:"text-gray-400 m-0 text-[10px] leading-relaxed",children:"Vercel needs permission to access your GitHub repositories. Connect your GitHub account, then come back and try again."}),d("div",{className:"flex items-center gap-2",children:[n("a",{href:"https://vercel.com/account/login-connections",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Connect GitHub →"}),n("button",{type:"button",onClick:()=>{M(null),L()},className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] rounded px-2.5 py-1 cursor-pointer transition-colors",children:"Retry"})]})]})]}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:1,done:I,active:B===1}),n("span",{className:"text-xs font-medium text-white",children:"Create Account & Connect"}),I&&F.user&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:F.user.username})]}),B===1&&d("div",{className:"ml-7 space-y-2.5",children:[d("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"a) Create a free Vercel account"}),n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Sign up with GitHub, GitLab, or email. The free Hobby plan includes unlimited deployments and custom domains."}),n("a",{href:"https://vercel.com/signup",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Sign up at vercel.com →"})]}),d("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"b) Create an API token"}),n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"This lets CodeYam verify your setup and check your project configuration. Go to Account Settings → Tokens → Create."}),n("a",{href:"https://vercel.com/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Open token settings →"})]}),d("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"c) Paste your token here"}),F.hasToken&&!F.tokenVerified&&n("p",{className:"text-[11px] text-amber-400 m-0",children:"A token was found but it didn't work. Try creating a new one and pasting it below."}),d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"Paste your Vercel token",value:i,onChange:Z=>l(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&J()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",onClick:J,disabled:c||!i.trim(),className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:c?"Verifying...":"Connect"})]}),n("p",{className:"text-[10px] text-gray-600 m-0",children:"Stored in .env.local (gitignored — never committed)"})]})]})]}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:2,done:K,active:B===2}),n("span",{className:`text-xs font-medium ${B>=2?"text-white":"text-gray-600"}`,children:"Link Project"}),K&&F.projectName&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:F.projectName})]}),K&&d("div",{className:"ml-7 space-y-1.5",children:[d("div",{className:"flex items-center gap-3",children:[F.dashboardUrl&&n("a",{href:F.dashboardUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Dashboard →"}),((oe=F.lastDeployment)==null?void 0:oe.url)&&d("a",{href:F.lastDeployment.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:[F.lastDeployment.url.replace("https://","")," →"]})]}),F.lastDeployment&&!S&&d("div",{className:"flex items-center gap-2 text-[10px] text-gray-500",children:[d("span",{children:["Deployed"," ",(()=>{const Z=Date.now()-F.lastDeployment.createdAt,re=Math.floor(Z/6e4);if(re<1)return"just now";if(re<60)return`${re}m ago`;const ue=Math.floor(re/60);return ue<24?`${ue}h ago`:`${Math.floor(ue/24)}d ago`})()]}),n("span",{className:"text-gray-600",children:"·"}),d("span",{className:F.lastDeployment.commitsSince>0?"text-amber-400":"text-gray-500",children:[F.lastDeployment.commitsSince," commit",F.lastDeployment.commitsSince===1?"":"s"," since"]}),n("button",{type:"button",disabled:w,onClick:()=>{M(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(Z=>Z.json()).then(Z=>{Z.ok&&Z.deployment?k({id:Z.deployment.id,state:Z.deployment.state||"QUEUED",url:Z.deployment.url,errorMessage:null,logsUrl:null}):M(Z.error||"Deployment failed")}).catch(()=>M("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors underline",children:w?"Starting...":"Redeploy"})]}),S&&d("div",{className:`bg-[#2a2a2a] border rounded-md px-3 py-2 space-y-1.5 ${S.state==="ERROR"?"border-red-500/40":S.state==="READY"?"border-green-500/40":"border-[#D7FF63]/30"}`,children:[d("div",{className:"flex items-center gap-2",children:[S.state==="READY"?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):S.state==="ERROR"||S.state==="CANCELED"?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-red-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 12 12",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-[#D7FF63]/30 flex items-center justify-center animate-pulse",children:n("span",{className:"w-2 h-2 rounded-full bg-[#D7FF63]"})}),n("span",{className:"text-[11px] text-white font-medium",children:S.state==="READY"?"Deployed successfully":S.state==="ERROR"?"Deployment failed":S.state==="CANCELED"?"Deployment canceled":S.state==="BUILDING"?"Building...":"Deploying..."})]}),S.state==="READY"&&S.url&&d("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors block",children:[S.url.replace("https://","")," →"]}),S.state==="ERROR"&&d("div",{className:"space-y-1",children:[S.errorMessage&&n("pre",{className:"text-[10px] text-red-300 bg-[#1a1a1a] rounded px-2 py-1.5 m-0 whitespace-pre-wrap font-mono overflow-x-auto max-h-24 overflow-y-auto",children:S.errorMessage}),d("div",{className:"flex items-center gap-2",children:[S.logsUrl&&n("a",{href:S.logsUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"View full logs →"}),n("button",{type:"button",onClick:()=>{k(null),M(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(Z=>Z.json()).then(Z=>{Z.ok&&Z.deployment?k({id:Z.deployment.id,state:Z.deployment.state||"QUEUED",url:Z.deployment.url,errorMessage:null,logsUrl:null}):M(Z.error||"Deployment failed")}).catch(()=>M("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[10px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] rounded px-2 py-0.5 cursor-pointer transition-colors",children:"Retry"}),n("button",{type:"button",onClick:()=>H(`## Deployment Error
|
|
701
|
+
The deployment failed with this error:
|
|
702
|
+
\`\`\`
|
|
703
|
+
${S.errorMessage||"Unknown error"}
|
|
704
|
+
\`\`\`
|
|
705
|
+
${S.logsUrl?`Full logs: ${S.logsUrl}`:""}
|
|
706
|
+
|
|
707
|
+
Help the user understand what went wrong and how to fix it. Read their project config files (package.json, next.config.ts, prisma/schema.prisma) if needed to diagnose the issue.`),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2 py-0.5 cursor-pointer transition-colors",children:"Debug with AI"})]})]})]}),F.lastDeployment===null&&!S&&d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2 space-y-1.5",children:[n("p",{className:"text-[11px] text-amber-400 m-0",children:"Not deployed yet"}),n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Your project is linked but hasn't been deployed. Push your code to GitHub to trigger an automatic deploy, or deploy now directly."}),n("button",{type:"button",disabled:w,onClick:()=>{M(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(Z=>Z.json()).then(Z=>{Z.ok&&Z.deployment?k({id:Z.deployment.id,state:Z.deployment.state||"QUEUED",url:Z.deployment.url,errorMessage:null,logsUrl:null}):M(Z.error||"Deployment failed")}).catch(()=>M("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:w?"Starting...":"Deploy now"})]})]}),B===2&&d("div",{className:"ml-7 space-y-2",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"A Vercel project is where your app lives once deployed. If you signed up with GitHub, Vercel can import the repo directly. Otherwise, create a new project and connect your repository."}),y?n("div",{children:n("span",{className:"text-[11px] text-gray-500",children:"Loading your Vercel projects..."})}):j&&p.length===0?n("div",{className:"space-y-2",children:T?d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"No Vercel projects found on your account."}),d("p",{className:"text-[10px] text-gray-500 m-0",children:["Create one linked to"," ",n("span",{className:"text-gray-300 font-mono",children:T}),"? Vercel will auto-deploy when you push."]}),n("button",{type:"button",onClick:L,disabled:v,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:v?"Creating...":"Create Vercel project"})]}):d("div",{className:"space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-400 m-0",children:"No Vercel projects found. Create one and import your repository:"}),n("a",{href:"https://vercel.com/new",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Create at vercel.com/new →"}),d("p",{className:"text-[10px] text-gray-600 m-0",children:["Then"," ",n("button",{type:"button",onClick:()=>{D(!1),ne.current=!1,A()},className:"text-[#D7FF63]/60 hover:text-[#D7FF63] bg-transparent border-none p-0 cursor-pointer text-[10px] underline",children:"re-check"})," ","to find it."]})]})}):p.length>0?d("div",{className:"space-y-2",children:[T&&!m&&d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"No existing project matches this repo."}),d("p",{className:"text-[10px] text-gray-500 m-0",children:["Create a new Vercel project linked to"," ",n("span",{className:"text-gray-300 font-mono",children:T}),"? Vercel will auto-deploy when you push."]}),n("button",{type:"button",onClick:L,disabled:v,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:v?"Creating...":"Create Vercel project"})]}),p.length>0&&d("div",{className:"space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0",children:m?"Select the project for this app:":"Or select an existing project:"}),n("div",{className:"space-y-1",children:p.map(Z=>d("button",{type:"button",onClick:()=>E(Z.id,Z.name),disabled:x,className:`w-full text-left rounded px-2.5 py-1.5 border transition-colors cursor-pointer flex items-center gap-2 ${Z.id===m?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("span",{className:"text-xs text-white flex-1",children:Z.name}),Z.framework&&n("span",{className:"text-[10px] text-gray-500",children:Z.framework}),Z.id===m&&n("span",{className:"text-[9px] text-[#D7FF63] bg-[#D7FF63]/10 px-1 py-px rounded",children:"matches repo"})]},Z.id))})]})]}):null]})]}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:3,done:Y,active:B===3}),n("span",{className:`text-xs font-medium ${B>=3?"text-white":"text-gray-600"}`,children:"Environment Variables"}),B===3&&V>0&&d("span",{className:"text-[10px] text-gray-400 ml-auto",children:[Q,"/",V," on Vercel"]})]}),B===3&&F.envVarsChecked&&n("div",{className:"ml-7 space-y-1.5",children:V===0?n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Your app doesn't use any third-party services that need secrets yet. When you add services like a database or payment provider, their required keys will appear here."}):d(ve,{children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"These are the secrets your app needs to run in production. They must be added to your Vercel project so deployed builds can access them."}),n("div",{className:"space-y-1 mt-1",children:F.envVars.map(Z=>d("div",{className:"flex items-center gap-2",children:[Z.configuredOnVercel?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-amber-500/30 flex items-center justify-center",children:n("span",{className:"w-2 h-2 rounded-full bg-amber-400"})}),n("span",{className:"text-xs text-gray-300 font-mono flex-1 truncate",children:Z.key}),n("span",{className:"text-[10px] text-gray-500",children:Z.service})]},Z.key))}),Q<V&&d("p",{className:"text-[10px] text-gray-500 m-0 mt-1.5 leading-relaxed",children:["Add missing variables in your"," ",n("a",{href:`https://vercel.com/~/project/${F.projectName||""}/settings/environment-variables`,target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/60 hover:text-[#D7FF63] no-underline",children:"Vercel project settings"})," ","→ Environment Variables. Then"," ",n("button",{type:"button",onClick:W,className:"text-[#D7FF63]/60 hover:text-[#D7FF63] bg-transparent border-none p-0 cursor-pointer text-[10px] underline",children:"re-check"}),"."]})]})}),B===3&&!F.envVarsChecked&&d("div",{className:"ml-7 space-y-1",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Check which secrets your app needs and whether they're configured on Vercel."}),n("button",{type:"button",onClick:W,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:"Check environment variables"})]})]}),O&&R?n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(O,{prompt:R,height:400,onClose:()=>{U(null),z(null),W()}})}):n("button",{type:"button",onClick:()=>H(),className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] hover:border-[#555] rounded px-2.5 py-1.5 cursor-pointer transition-colors w-full mt-1",children:"I'm stuck — chat with AI"})]})}function xd({github:e,onSave:t,onShowChat:r}){const[s,o]=P(null),[a,i]=P(!0),[l,c]=P(""),[u,p]=P(!1),[h,m]=P(!1),[f,y]=P([]),[g,x]=P(!1),[b,v]=P(!1),[N,w]=P(!1),[C,S]=P(null),[k,T]=P(!1),[_,$]=P(null),M=ce(()=>{i(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"full-status"})}).then(I=>I.json()).then(I=>{o(I),$(null)}).catch(()=>$("Failed to check status")).finally(()=>i(!1))},[]);se(()=>{M()},[M]);const R=()=>{m(!0),$(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"init-git"})}).then(I=>I.json()).then(I=>{I.ok?M():$(I.error||"Failed to initialize git")}).catch(()=>$("Failed to initialize git")).finally(()=>m(!1))},z=()=>{l.trim()&&(p(!0),$(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"save-token",token:l.trim()})}).then(I=>I.json()).then(I=>{I.ok?(c(""),M()):$(I.error||"Token verification failed")}).catch(()=>$("Failed to save token")).finally(()=>p(!1)))},O=()=>{x(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"list-repos"})}).then(I=>I.json()).then(I=>{I.ok&&(y(I.repos||[]),S(I.suggestedRepoName||null))}).catch(()=>{}).finally(()=>x(!1))},U=()=>{v(!0),$(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"create-repo"})}).then(I=>I.json()).then(I=>{I.ok?(t({owner:I.repo.owner,repo:I.repo.name,repoUrl:I.repo.url}),M()):$(I.error||"Failed to create repository")}).catch(()=>$("Failed to create repository")).finally(()=>v(!1))},W=I=>{w(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"link-repo",repoUrl:I.cloneUrl,owner:I.fullName.split("/")[0],repo:I.name})}).then(K=>K.json()).then(K=>{K.ok&&(t({owner:I.fullName.split("/")[0],repo:I.name,repoUrl:I.url}),M())}).catch(()=>{}).finally(()=>w(!1))},J=()=>{T(!0),$(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"push"})}).then(I=>I.json()).then(I=>{I.ok?M():$(I.error||"Push failed")}).catch(()=>$("Push failed")).finally(()=>T(!1))},j=s||{gitInitialized:!1,hasGitignore:!1,hasRemote:!1,isGitHub:!1,ghCliInstalled:!1,ghCliAuthenticated:!1,hasToken:!1,tokenVerified:!1,user:null,githubRepo:null,hasCommits:!1,pushed:!1},D=j.gitInitialized,A=j.ghCliAuthenticated||j.tokenVerified,L=j.hasRemote&&j.isGitHub,E=D?A?3:2:1,F=ye(!1);return se(()=>{E===3&&!L&&!F.current&&f.length===0&&!g&&(F.current=!0,O())},[E,L]),a&&!s?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:n("span",{className:"text-xs text-gray-500",children:"Checking GitHub setup..."})}):d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333] space-y-3",children:[d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"GitHub Setup"}),n("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:"GitHub stores your code and tracks changes. Push your code to a repository so it’s backed up, versioned, and ready for collaboration or deployment."})]}),_&&n("div",{className:"text-[11px] text-red-400 bg-red-400/10 rounded px-2 py-1.5",children:_}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:1,done:D,active:E===1}),n("span",{className:"text-xs font-medium text-white",children:"Initialize Git"}),D&&j.hasGitignore&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:"ready"})]}),E===1&&d("div",{className:"ml-7 space-y-2",children:[d("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["Git tracks every change to your code so you can undo mistakes, see history, and collaborate. This initializes a local git repository and creates a ",n("code",{children:".gitignore"})," file to keep sensitive files out of version control."]}),n("button",{type:"button",onClick:R,disabled:h,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:h?"Initializing...":"Initialize Git"})]})]}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:2,done:A,active:E===2}),n("span",{className:`text-xs font-medium ${E>=2?"text-white":"text-gray-600"}`,children:"Connect to GitHub"}),A&&j.user&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:j.user.username})]}),E===2&&d("div",{className:"ml-7 space-y-2.5",children:[d("div",{className:"space-y-1",children:[d("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:["a) Install & authenticate with GitHub CLI",j.ghCliInstalled&&!j.ghCliAuthenticated&&n("span",{className:"text-[10px] text-green-400 ml-1.5",children:"(installed)"})]}),d("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["The GitHub CLI (",n("code",{children:"gh"}),") is the easiest way to authenticate. Install it, then run ",n("code",{children:"gh auth login"})," in your terminal."]}),d("div",{className:"flex items-center gap-2",children:[!j.ghCliInstalled&&n("a",{href:"https://cli.github.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Install GitHub CLI →"}),n("button",{type:"button",onClick:M,disabled:a,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:a?"Checking...":"Check Authentication"})]})]}),d("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"b) Or paste a Personal Access Token"}),d("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["Create a token with ",n("strong",{children:"repo"})," scope. This is stored in .env.local (never committed)."]}),n("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=CodeYam",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Create token on GitHub →"}),j.hasToken&&!j.tokenVerified&&n("p",{className:"text-[11px] text-amber-400 m-0",children:"A token was found but it didn't work. Try creating a new one."}),d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"Paste your GitHub token",value:l,onChange:I=>c(I.target.value),onKeyDown:I=>{I.key==="Enter"&&z()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",onClick:z,disabled:u||!l.trim(),className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:u?"Verifying...":"Connect"})]}),n("p",{className:"text-[10px] text-gray-600 m-0",children:"Stored in .env.local (gitignored — never committed)"})]})]})]}),d("div",{className:"space-y-1.5",children:[d("div",{className:"flex items-center gap-2",children:[n(sr,{step:3,done:L,active:E===3}),n("span",{className:`text-xs font-medium ${E>=3?"text-white":"text-gray-600"}`,children:"Create or Link Repository"}),L&&j.githubRepo&&d("span",{className:"text-[10px] text-gray-400 ml-auto",children:[j.githubRepo.owner,"/",j.githubRepo.repo]})]}),E===3&&L&&j.githubRepo&&d("div",{className:"ml-7 space-y-2",children:[d("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:["Connected to"," ",d("a",{href:`https://github.com/${j.githubRepo.owner}/${j.githubRepo.repo}`,target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:[j.githubRepo.owner,"/",j.githubRepo.repo]})]}),j.hasCommits&&!j.pushed&&d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"Push your code to GitHub"}),n("p",{className:"text-[10px] text-gray-500 m-0",children:"Your local commits haven't been pushed yet. Push now to back up your code and make it available on GitHub."}),n("button",{type:"button",onClick:J,disabled:k,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:k?"Pushing...":"Push to GitHub"})]}),j.pushed&&n("p",{className:"text-[10px] text-green-400 m-0",children:"Code is pushed and up to date."})]}),E===3&&!L&&d("div",{className:"ml-7 space-y-2",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Create a new GitHub repository for this project or link to an existing one."}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"Create a new private repository"}),n("p",{className:"text-[10px] text-gray-500 m-0",children:"Creates a repository on GitHub and sets it as the remote for this project."}),n("button",{type:"button",onClick:U,disabled:b,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:b?"Creating...":"Create repository"})]}),f.length===0&&g&&n("span",{className:"text-[11px] text-gray-500",children:"Loading your repositories..."}),f.length>0&&d("div",{className:"space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0",children:"Or link an existing repository:"}),n("div",{className:"space-y-1",children:f.map(I=>d("button",{type:"button",onClick:()=>W(I),disabled:N,className:`w-full text-left rounded px-2.5 py-1.5 border transition-colors cursor-pointer flex items-center gap-2 ${I.name===C?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("span",{className:"text-xs text-white flex-1",children:I.fullName}),I.private&&n("span",{className:"text-[10px] text-gray-500",children:"private"}),I.name===C&&n("span",{className:"text-[9px] text-[#D7FF63] bg-[#D7FF63]/10 px-1 py-px rounded",children:"matches project"})]},I.fullName))})]})]})]}),r&&n("button",{type:"button",onClick:r,className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] hover:border-[#555] rounded px-2.5 py-1.5 cursor-pointer transition-colors w-full mt-1",children:"Need help? Ask Claude about GitHub setup"})]})}function bd({hosting:e,onSave:t,onEditNavigate:r,defaultEditing:s=!1,onShowChat:o}){const a=(e==null?void 0:e.provider)||null,[i,l]=P(s&&!a),c=u=>{t({provider:u}),l(!1)};if(a==="vercel")return n(V5,{hosting:e,onSave:t});if(!i&&a){const u=yd.find(p=>p.id===a);return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Hosting"}),u?n("div",{className:"flex items-center gap-2 bg-[#2a2a2a] border border-[#D7FF63]/40 rounded-md px-3 py-2",children:d("div",{className:"flex-1",children:[n("div",{className:"text-sm font-medium text-white",children:u.name}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:u.description})]})}):n("div",{className:"text-xs text-gray-400",children:a}),n("button",{type:"button",onClick:r??(()=>l(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Change >"})]})}return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Choose a hosting provider"}),n("div",{className:"space-y-2",children:yd.map(u=>d("button",{type:"button",onClick:()=>c(u.id),className:`w-full text-left rounded-md px-3 py-2.5 border transition-colors cursor-pointer ${a===u.id?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("div",{className:"text-sm font-medium text-white",children:u.name}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:u.description}),n("div",{className:"flex gap-1.5 mt-1.5",children:u.services.map(p=>n("span",{className:"text-[10px] text-gray-300 bg-[#333] px-1.5 py-0.5 rounded",children:p},p))})]},u.id))}),a&&n("button",{type:"button",onClick:()=>l(!1),className:"text-[11px] text-gray-400 hover:text-white bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors",children:"Cancel"})]})}function vd({serviceName:e,serviceUrl:t,envKeys:r,environmentVariables:s,onSaveEnvVar:o,onEditNavigate:a,defaultEditing:i=!1}){const[l,c]=P(i),[u,p]=P({}),h=pe(()=>{const g=new Set;for(const x of s){const b=x.key||x.name;b&&x.value&&g.add(b)}return g},[s]),m=r.filter(g=>h.has(g)).length,f=m===r.length,y=g=>{const x=u[g];x!==void 0&&x!==""&&(o(g,x),p(b=>{const v={...b};return delete v[g],v}))};return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Credentials"}),t&&n("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/60 hover:text-[#D7FF63] no-underline",children:"docs →"})]}),n("div",{className:"space-y-1.5",children:r.map(g=>{const x=h.has(g),b=u[g]!==void 0;return d("div",{className:"flex items-center gap-2",children:[x?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-amber-500/30 flex items-center justify-center",children:n("span",{className:"w-2 h-2 rounded-full bg-amber-400"})}),n("span",{className:"text-xs text-gray-300 font-mono flex-1 truncate",children:g}),x&&!b?n("span",{className:"text-[10px] text-gray-500",children:"configured"}):l||b?d("div",{className:"flex items-center gap-1",children:[n("input",{type:"text",placeholder:"value",value:u[g]||"",onChange:v=>p(N=>({...N,[g]:v.target.value})),onKeyDown:v=>{v.key==="Enter"&&y(g)},className:"bg-[#1a1a1a] border border-[#444] rounded px-1.5 py-0.5 text-xs text-white w-32 outline-none focus:border-[#D7FF63]/50"}),n("button",{type:"button",onClick:()=>y(g),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"Save"})]}):n("button",{type:"button",onClick:()=>p(v=>({...v,[g]:""})),className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"add"})]},g)})}),d("div",{className:"flex items-center justify-between mt-2",children:[n("span",{className:"text-[10px] text-gray-500",children:f?"All keys configured":`${m} of ${r.length} keys configured`}),!l&&!f&&n("button",{type:"button",onClick:a??(()=>c(!0)),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"Configure all >"})]})]})}function K5({onBack:e,onSwitchToBuild:t,onSwitchToHistory:r,onNavigateToDesignSystem:s,onNavigateToTechStack:o,expandedTasks:a,onExpandedTasksChange:i}){const{revalidate:l}=Bt(),[c,u]=P(null),[p,h]=P(!1),[m,f]=P(null),y=ce(()=>{fetch("/api/editor-roadmap").then(j=>j.json()).then(j=>u(j)).catch(()=>{})},[]);se(()=>{y()},[y]);const g=(c==null?void 0:c.plan.some(j=>j.id==="plan-design-system"&&j.completed))??!1;se(()=>{if(!g){f(null);return}fetch("/api/editor-design-system").then(j=>j.json()).then(j=>{j.exists&&j.content?f(Ka(j.content)):f(null)}).catch(()=>f(null))},[g]);const x=ce(j=>{h(!0),fetch("/api/editor-roadmap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}).then(D=>D.json()).then(()=>y()).catch(()=>{}).finally(()=>h(!1))},[y]),b=ce((j,D)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectTitle:j,projectDescription:D})}).then(()=>y()).catch(()=>{})},[y]),v=ce((j,D)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenSizes:j,projectScreenSizes:D})}).then(()=>{y(),l()}).catch(()=>{})},[y,l]),N=ce(j=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hosting:j})}).then(()=>y()).catch(()=>{})},[y]),w=ce(j=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github:j})}).then(()=>y()).catch(()=>{})},[y]),C=ce((j,D)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({addEnvironmentVariable:{key:j,value:D}})}).then(()=>y()).catch(()=>{})},[y]),S=ce((j,D)=>{if(!c)return;const A=c[j].filter(L=>L.id!==D);u({...c,[j]:A}),x({[j]:A})},[c,x]),[k,T]=P(null),_=ye(null),$=ye(0),M=ce(j=>{const D=new Set(a);D.has(j)?D.delete(j):D.add(j),i(D)},[a,i]),R=ce(j=>{_.current&&($.current=_.current.scrollTop),T(j)},[]),z=ce(()=>{T(null),requestAnimationFrame(()=>{_.current&&(_.current.scrollTop=$.current)})},[]);if(!c)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading roadmap..."})});const O=c.plan.filter(j=>j.completed).length,U=c.deploy.filter(j=>j.completed).length,W=c.buildSessionCount===1?"1 working session completed":`${c.buildSessionCount} working sessions completed`,J=k&&([...c.plan,...c.deploy].find(j=>j.id===k)??null);if(J){const j=J.id==="plan-project-name"&&J.completed?n(md,{projectTitle:c.projectTitle,projectDescription:c.projectDescription,onSave:b,defaultEditing:!0}):J.id==="plan-screen-sizes"&&J.completed?n(gd,{screenSizes:c.screenSizes,projectScreenSizes:c.projectScreenSizes,defaultScreenSize:c.defaultScreenSize,appFormats:c.appFormats,onSave:v,defaultEditing:!0}):J.id==="plan-github"?n(xd,{github:c.github,onSave:w}):J.id==="deploy-hosting"?n(bd,{hosting:c.hosting,onSave:N,defaultEditing:!0}):J.serviceRef&&c.techStack?(()=>{var L;const D=c.techStack[J.serviceRef.category],A=D==null?void 0:D.find(E=>E.name===J.serviceRef.name);return(L=A==null?void 0:A.envKeys)!=null&&L.length?n(vd,{serviceName:A.name,serviceUrl:A.url,envKeys:A.envKeys,environmentVariables:c.environmentVariables,onSaveEnvVar:C,defaultEditing:!0}):null})():null;return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:z,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center gap-2.5",children:[n("h2",{className:"text-lg font-medium text-white mt-0 mb-0",children:J.label}),J.completed&&n("span",{className:"shrink-0 w-5 h-5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]}),j?n("div",{children:j}):n("p",{className:"text-sm text-gray-500",children:J.completed?"This task has been completed.":"This task has not been started yet."}),p&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}return n("div",{ref:_,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-6",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to App"]}),n("h2",{className:"text-lg font-medium text-white mt-0 mb-6",children:"Roadmap"}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[n(hd,{title:"Plan",completedCount:O,totalCount:c.plan.length}),n("div",{className:"mt-2",children:c.plan.map(j=>d(pd,{todo:j,expanded:a.has(j.id),onToggle:()=>M(j.id),onRemove:j.userCreated?()=>S("plan",j.id):void 0,children:[j.id==="plan-project-name"&&j.completed&&n(md,{projectTitle:c.projectTitle,projectDescription:c.projectDescription,onSave:b,onEditNavigate:()=>R(j.id)}),j.id==="plan-tech-stack"&&n(J5,{techStack:c.techStack,onNavigate:o}),j.id==="plan-design-system"&&j.completed&&m&&n(W5,{designSystem:m,onEdit:s}),j.id==="plan-screen-sizes"&&j.completed&&n(gd,{screenSizes:c.screenSizes,projectScreenSizes:c.projectScreenSizes,defaultScreenSize:c.defaultScreenSize,appFormats:c.appFormats,onSave:v,onEditNavigate:()=>R(j.id)}),j.id==="plan-github"&&n(xd,{github:c.github,onSave:w})]},j.id))})]}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-sm font-medium text-white m-0",children:"Build"}),n("span",{className:"text-xs text-gray-500",children:W})]}),c.featureName&&d("div",{className:"mt-3 flex items-center gap-2",children:[n("span",{className:"text-xs text-gray-400",children:"Active:"}),d("button",{type:"button",onClick:t,className:"text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:[c.featureName,c.editorStepLabel&&d("span",{className:"text-gray-500 ml-1",children:["— ",c.editorStepLabel]})]})]}),!c.featureName&&d("div",{className:"mt-2",children:[n("p",{className:"text-xs text-gray-500 m-0",children:"No work is in progress."}),n("button",{type:"button",onClick:t,className:"text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1 cursor-pointer transition-colors",children:"Start the next working session >"})]}),c.recentEntries.length>0&&d("div",{className:"mt-3 space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Recent"}),c.recentEntries.map(j=>d("button",{type:"button",onClick:r,className:"w-full flex items-center gap-2 py-1 px-0 bg-transparent border-none cursor-pointer text-left group",children:[n("span",{className:`${Y5[j.type]||"bg-gray-600"} text-white text-[8px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:j.type}),n("span",{className:"text-xs text-gray-300 group-hover:text-white transition-colors truncate flex-1",children:j.title}),n("span",{className:"text-[10px] text-gray-600 shrink-0",children:U5(j.time)})]},j.time)),c.buildSessionCount>3&&n("button",{type:"button",onClick:r,className:"text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 pt-1 cursor-pointer transition-colors",children:"View all working session results >"})]})]}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[n(hd,{title:"Deploy",completedCount:U,totalCount:c.deploy.length}),n("div",{className:"mt-2",children:c.deploy.map(j=>n(pd,{todo:j,expanded:a.has(j.id),onToggle:()=>M(j.id),onRemove:j.userCreated?()=>S("deploy",j.id):void 0,children:j.id==="deploy-hosting"?n(bd,{hosting:c.hosting,onSave:N,onEditNavigate:()=>R(j.id)}):j.serviceRef&&c.techStack?(()=>{var L;const D=c.techStack[j.serviceRef.category],A=D==null?void 0:D.find(E=>E.name===j.serviceRef.name);return(L=A==null?void 0:A.envKeys)!=null&&L.length?n(vd,{serviceName:A.name,serviceUrl:A.url,envKeys:A.envKeys,environmentVariables:c.environmentVariables,onSaveEnvVar:C,onEditNavigate:()=>R(j.id)}):n("p",{className:"text-xs text-gray-500 m-0 mt-1 mb-2",children:j.completed?"Completed":"Not started yet"})})():n("p",{className:"text-xs text-gray-500 m-0 mt-1 mb-2",children:j.completed?"Completed":"Not started yet"})},j.id))})]}),p&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}function G5({color:e,onColorChange:t}){const r=ye(null),s=q5(e.value),o=e.value.startsWith("#");return d("div",{className:"flex flex-col gap-1",children:[n("button",{type:"button",className:"w-full h-10 rounded-md border border-[#444] cursor-pointer relative group",style:{backgroundColor:e.value},onClick:()=>{var a;return o&&((a=r.current)==null?void 0:a.click())},title:`--${e.name}: ${e.value}${e.comment?` (${e.comment})`:""}`,children:o&&n("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30 rounded-md",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})}),o&&n("input",{ref:r,type:"color",value:s,onChange:a=>t(e.name,a.target.value),className:"sr-only"}),d("div",{className:"text-[9px] font-mono text-gray-500 truncate",title:`--${e.name}`,children:["--",e.name]}),n("div",{className:"text-[9px] font-mono text-gray-600 truncate",children:e.value})]})}function q5(e){if(!e.startsWith("#"))return"#000000";const t=e.slice(1);return t.length===3?`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:t.length===6||t.length===8?`#${t.slice(0,6)}`:"#000000"}function Q5({group:e,colors:t,onColorChange:r}){const[s,o]=P(!1);return d("div",{className:"mb-4",children:[d("button",{type:"button",onClick:()=>o(!s),className:"flex items-center gap-1.5 text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-2 bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${s?"":"rotate-90"}`,children:n("path",{d:"M9 18l6-6-6-6"})}),e,d("span",{className:"text-gray-600 font-normal",children:["(",t.length,")"]})]}),!s&&n("div",{className:"grid grid-cols-5 gap-2",children:t.map(a=>n(G5,{color:a,onColorChange:r},`${a.group}-${a.name}`))})]})}function Z5({designSystem:e,rawMarkdown:t,onSave:r}){const s=e.colors.reduce((c,u)=>(c[u.group]||(c[u.group]=[]),c[u.group].push(u),c),{}),o=ce((c,u)=>{const p=O5(t,c,u);r(p)},[t,r]),[a,i]=P(e.fonts.length>0?e.fonts.join(", "):""),l=ce(()=>{if(!a.trim())return;const c=L5(t,`'${a.trim()}', sans-serif`);r(c)},[t,a,r]);return d("div",{className:"space-y-6",children:[Object.keys(s).length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Colors"}),Object.entries(s).map(([c,u])=>n(Q5,{group:c,colors:u,onColorChange:o},c))]}),e.fonts.length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Typography"}),d("div",{className:"flex items-center gap-2 mb-3",children:[n("label",{className:"text-[10px] text-gray-500 uppercase tracking-wider shrink-0",children:"Font"}),n("input",{type:"text",value:a,onChange:c=>i(c.target.value),onBlur:l,onKeyDown:c=>c.key==="Enter"&&l(),className:"flex-1 px-2 py-1 text-xs bg-[#222] border border-[#3d3d3d] rounded text-gray-300 outline-none focus:border-[#D7FF63]/50"})]}),e.typographyScale.length>0&&n("div",{className:"bg-[#222] rounded border border-[#333] overflow-hidden",children:d("table",{className:"w-full",children:[n("thead",{children:d("tr",{className:"border-b border-[#333]",children:[n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Style"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Size"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Weight"})]})}),n("tbody",{children:e.typographyScale.map(c=>d("tr",{className:"border-b border-[#333] last:border-b-0",children:[n("td",{className:"px-3 py-1.5 text-xs text-gray-300",children:c.style}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:c.size}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:c.weight})]},c.style))})]})})]}),e.radiusTokens.length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Border Radius"}),n("div",{className:"flex gap-3 flex-wrap",children:e.radiusTokens.map(c=>d("div",{className:"flex flex-col items-center gap-1",children:[n("div",{className:"w-10 h-10 bg-[#D7FF63]/20 border border-[#D7FF63]/40",style:{borderRadius:c.value}}),d("div",{className:"text-[9px] font-mono text-gray-500",children:["--",c.name]}),n("div",{className:"text-[9px] font-mono text-gray-600",children:c.value})]},c.name))})]})]})}function X5({content:e,onSave:t}){const[r,s]=P(e),[o,a]=P(!1);se(()=>{s(e),a(!1)},[e]);const i=ce(()=>{t(r),a(!1)},[r,t]);return d("div",{className:"flex flex-col gap-2 h-full",children:[n("textarea",{value:r,onChange:l=>{s(l.target.value),a(!0)},className:"flex-1 min-h-[400px] p-3 text-xs font-mono bg-[#1a1a1a] border border-[#3d3d3d] rounded-lg text-gray-300 outline-none focus:border-[#D7FF63]/50 resize-none leading-relaxed",spellCheck:!1}),d("div",{className:"flex items-center gap-2",children:[n("button",{type:"button",onClick:i,disabled:!o,className:`px-4 py-1.5 text-xs rounded-md font-medium transition-colors cursor-pointer ${o?"text-[#1e1e1e] bg-[#D7FF63] hover:bg-[#D7FF63]/80":"text-gray-500 bg-[#333] cursor-not-allowed"}`,children:"Save"}),o&&n("span",{className:"text-[10px] text-gray-500",children:"Unsaved changes"})]})]})}function eE({onClose:e}){return n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:`# Edit Design System
|
|
708
|
+
|
|
709
|
+
You are helping the user edit their design system file at \`.codeyam/design-system.md\`.
|
|
710
|
+
|
|
711
|
+
Read the current design system file first, then ask the user what they'd like to change. Common changes include:
|
|
712
|
+
- Changing colors (background, text, accent colors)
|
|
713
|
+
- Switching fonts or typography scale
|
|
714
|
+
- Adjusting spacing, radius, or shadow values
|
|
715
|
+
- Adding or removing theme modes (light/dark)
|
|
716
|
+
- Changing the overall aesthetic (minimal, bold, editorial, etc.)
|
|
717
|
+
|
|
718
|
+
After making changes, briefly summarize what was updated.`,height:500,onClose:e})})}function tE({onBack:e,onPreviewShowcase:t}){const[r,s]=P("visual"),[o,a]=P(null),[i,l]=P(null),[c,u]=P(!1),[p,h]=P(!1),m=ce(()=>{fetch("/api/editor-design-system").then(g=>g.json()).then(g=>{g.exists&&g.content&&(a(g.content),l(Ka(g.content)))}).catch(()=>{})},[]);se(()=>{m()},[m]),se(()=>{if(r!=="claude"||!p)return;const g=setInterval(m,3e3);return()=>clearInterval(g)},[r,p,m]);const f=ce(g=>{u(!0),a(g),l(Ka(g)),fetch("/api/editor-design-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:g})}).then(()=>{t()}).catch(()=>{}).finally(()=>u(!1))},[t]);if(!o||!i)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading design system..."})});const y=[{id:"visual",label:"Visual"},{id:"markdown",label:"Markdown"},{id:"claude",label:"Claude"}];return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center justify-between",children:[d("div",{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:i.name}),i.description&&n("p",{className:"text-xs text-gray-500 m-0 mt-1 max-w-md",children:i.description})]}),d("button",{type:"button",onClick:t,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}),"Preview Components"]})]}),n("div",{className:"flex gap-1 bg-[#222] rounded-lg p-0.5 w-fit border border-[#333]",children:y.map(g=>n("button",{type:"button",onClick:()=>{s(g.id),g.id==="claude"&&h(!0)},className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer border-none ${r===g.id?"bg-[#3a3a3a] text-white font-medium":"bg-transparent text-gray-500 hover:text-gray-300"}`,children:g.label},g.id))}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[r==="visual"&&n(Z5,{designSystem:i,rawMarkdown:o,onSave:f}),r==="markdown"&&n(X5,{content:o,onSave:f}),r==="claude"&&p&&n(eE,{onClose:()=>{h(!1),m()}}),r==="claude"&&!p&&d("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[n("p",{className:"text-xs text-gray-500",children:"Use Claude to make design system changes with natural language."}),n("button",{type:"button",onClick:()=>h(!0),className:"px-4 py-2 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Start Claude Chat"})]})]}),c&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}const Ds=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function nE({onBack:e}){const[t,r]=P(null),[s,o]=P(!1),[a,i]=P(!1),[l,c]=P({}),[u,p]=P(!1),h=typeof window<"u"?window.location.origin:"",m=ce(()=>{fetch("/api/editor-project-info").then(S=>S.json()).then(S=>{r(S.techStack||null),o(!0)}).catch(()=>o(!0))},[]);se(()=>{m()},[m]);const f=ce(S=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({techStack:S})}).then(()=>m()).catch(()=>{})},[m]),y=()=>{c(t?JSON.parse(JSON.stringify(t)):{}),i(!0)},g=()=>{const S={};for(const{key:k}of Ds){const T=l[k];T&&T.length>0&&(S[k]=T.filter(_=>_.name.trim()!==""))}f(S),i(!1)},x=S=>{c(k=>({...k,[S]:[...k[S]||[],{name:"",url:"",description:""}]}))},b=(S,k)=>{c(T=>({...T,[S]:(T[S]||[]).filter((_,$)=>$!==k)}))},v=(S,k,T,_)=>{c($=>({...$,[S]:($[S]||[]).map((M,R)=>R===k?{...M,[T]:_}:M)}))},N=(S,k,T)=>{const _=T.split(",").map($=>$.trim()).filter(Boolean);c($=>({...$,[S]:($[S]||[]).map((M,R)=>R===k?{...M,envKeys:_}:M)}))},w=pe(()=>`# Detect and Set Up Tech Stack
|
|
719
|
+
|
|
720
|
+
You are helping the user configure their project's tech stack in CodeYam.
|
|
721
|
+
|
|
722
|
+
## Instructions
|
|
723
|
+
|
|
724
|
+
1. Read \`package.json\` to find all dependencies and devDependencies
|
|
725
|
+
2. Check for framework config files: \`next.config.js\`, \`next.config.ts\`, \`tailwind.config.js\`, \`prisma/schema.prisma\`, \`tsconfig.json\`, \`vite.config.ts\`, etc.
|
|
726
|
+
3. Check \`.env\`, \`.env.example\`, \`.env.local\` for service references (e.g., STRIPE_SECRET_KEY, DATABASE_URL, OPENAI_API_KEY)
|
|
727
|
+
4. Categorize everything into: languages, frameworks, databases, services, libraries, infrastructure
|
|
728
|
+
|
|
729
|
+
## Tech Stack Categories
|
|
730
|
+
|
|
731
|
+
- **languages**: Programming languages (TypeScript, JavaScript, Python, etc.)
|
|
732
|
+
- **frameworks**: Application frameworks (Next.js, React, Express, etc.)
|
|
733
|
+
- **databases**: Database systems (PostgreSQL, SQLite, MongoDB, etc.)
|
|
734
|
+
- **services**: External services/APIs (Stripe, Auth0, SendGrid, AWS S3, etc.) — include \`url\` and \`envKeys\` for each
|
|
735
|
+
- **libraries**: Key libraries beyond the framework (Prisma, Tailwind CSS, Zod, etc.)
|
|
736
|
+
- **infrastructure**: Deployment/infrastructure tools (Vercel, Docker, etc.)
|
|
737
|
+
|
|
738
|
+
## Output Format
|
|
739
|
+
|
|
740
|
+
After scanning, POST the tech stack:
|
|
741
|
+
|
|
742
|
+
\`\`\`bash
|
|
743
|
+
curl -s -X POST ${h}/api/editor-project-info \\
|
|
744
|
+
-H "Content-Type: application/json" \\
|
|
745
|
+
-d '{"techStack":{"languages":[{"name":"TypeScript","url":"https://typescriptlang.org","description":"Statically typed JavaScript superset","version":"5"}],"frameworks":[{"name":"Next.js","url":"https://nextjs.org","description":"Full-stack React framework with SSR and API routes","version":"15"}],"databases":[{"name":"SQLite","url":"https://sqlite.org","description":"Embedded relational database"}],"services":[{"name":"Stripe","url":"https://stripe.com","description":"Payment processing and billing","envKeys":["STRIPE_SECRET_KEY","STRIPE_PUBLISHABLE_KEY"]}],"libraries":[{"name":"Prisma","url":"https://prisma.io","description":"Type-safe database ORM and query builder","version":"7"}],"infrastructure":[]}}'
|
|
746
|
+
\`\`\`
|
|
747
|
+
|
|
748
|
+
Replace the example values with what you actually detect. For each item:
|
|
749
|
+
- \`name\` (required): Technology name
|
|
750
|
+
- \`url\` (required): Link to homepage or docs
|
|
751
|
+
- \`description\` (required): Brief description of what it does or how it's used in this project
|
|
752
|
+
- \`version\` (optional): Version number
|
|
753
|
+
- \`envKeys\` (optional): Array of environment variable names associated with this tech
|
|
754
|
+
|
|
755
|
+
Omit empty categories. After posting, briefly summarize what was detected.`,[h]),C=t&&Ds.some(({key:S})=>t[S]&&t[S].length>0);return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center justify-between",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Tech Stack"}),n("div",{className:"flex items-center gap-2",children:s&&!a&&!u&&(C?n("button",{type:"button",onClick:y,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Edit"}):n("button",{type:"button",onClick:()=>p(!0),className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude"}))})]}),u&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qt,{prompt:w,height:400,onClose:()=>{p(!1),m()}})}),a&&d("div",{className:"space-y-4",children:[n("button",{type:"button",onClick:()=>{i(!1),p(!0)},className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Re-detect with Claude"}),Ds.map(({key:S,label:k})=>{const T=l[S]||[];return d("div",{children:[d("div",{className:"flex items-center justify-between mb-2",children:[n("label",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider",children:k}),n("button",{type:"button",onClick:()=>x(S),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:"+ Add"})]}),T.map((_,$)=>d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-2.5 mb-2 space-y-1.5",children:[d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:_.name,onChange:M=>v(S,$,"name",M.target.value),placeholder:"Name *",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-medium"}),n("input",{type:"text",value:_.version||"",onChange:M=>v(S,$,"version",M.target.value),placeholder:"Version",className:"w-20 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:()=>b(S,$),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]}),n("input",{type:"text",value:_.url||"",onChange:M=>v(S,$,"url",M.target.value),placeholder:"URL * (e.g. https://stripe.com)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:_.description||"",onChange:M=>v(S,$,"description",M.target.value),placeholder:"Description * (e.g. Payment processing and billing)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:(_.envKeys||[]).join(", "),onChange:M=>N(S,$,M.target.value),placeholder:"ENV_KEYS (comma-separated, e.g. STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY)",className:"w-full px-2 py-1 text-[10px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-400 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-mono"})]},$)),T.length===0&&n("div",{className:"text-[11px] text-gray-600 italic py-1",children:"No items"})]},S)}),d("div",{className:"flex gap-2 pt-1",children:[n("button",{type:"button",onClick:g,className:"px-4 py-1.5 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>i(!1),className:"px-4 py-1.5 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]}),!a&&!u&&n(ve,{children:C?n("div",{className:"space-y-4",children:Ds.map(({key:S,label:k})=>{const T=t[S];return!T||T.length===0?null:d("div",{children:[n("div",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:k}),n("div",{className:"space-y-2",children:T.map((_,$)=>d("div",{className:"bg-[#2a2a2a] rounded-lg px-3 py-2.5",children:[d("div",{className:"flex items-center gap-2",children:[_.url?n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-200 hover:text-[#D7FF63] transition-colors",children:_.name}):n("span",{className:"text-sm font-medium text-gray-200",children:_.name}),_.version&&d("span",{className:"text-[11px] text-gray-500",children:["v",_.version]}),_.url&&n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-gray-600 hover:text-gray-400 transition-colors truncate",children:_.url.replace(/^https?:\/\//,"")})]}),_.description&&n("div",{className:"text-xs text-gray-400 mt-1",children:_.description}),_.envKeys&&_.envKeys.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-1.5",children:_.envKeys.map((M,R)=>n("span",{className:"text-[10px] text-[#D7FF63]/60 bg-[#D7FF63]/10 px-1.5 py-0.5 rounded font-mono",children:M},R))})]},$))})]},S)})}):n("div",{className:"text-xs text-gray-500 italic py-4",children:"No tech stack configured yet. Use the buttons above to set up your project's tech stack."})})]})})}function rE({hasProject:e,scenarios:t,analyzedEntities:r,allEntities:s=[],glossaryFunctions:o=[],cachedTestResults:a={},glossaryEntries:i=[],projectRoot:l,activeScenarioId:c,onScenarioSelect:u,onAnalyzedScenarioSelect:p,onSwitchToBuild:h,onSwitchToHistory:m,zoomComponent:f,focusedEntity:y,onZoomChange:g,entityImports:x,pageFilePaths:b={},projectTitle:v,projectDescription:N,migrationMode:w="none",migrationState:C,onStartMigration:S,breadcrumbItems:k=[],onReseedPreview:T,isAdmin:_=!1,roadmapView:$=!1,onRoadmapViewChange:M,designSystemView:R=!1,onDesignSystemViewChange:z,onPreviewDesignSystem:O,techStackView:U=!1,onTechStackViewChange:W}){const{pageGroups:J,componentGroups:j}=pe(()=>nl(t),[t]),D=pe(()=>Hp(J,j),[J,j]),A=pe(()=>new Set(r.map(be=>be.sha)),[r]),L=pe(()=>d5(x||{}),[x]),E=ce(be=>u5(be,A,s,L),[A,s,L]),F=pe(()=>{const be=new Map;for(const Ee of s)be.set(Ee.sha,Ee.name);return be},[s]),I=pe(()=>p5(J,j,D,E),[J,j,D,E]),K=pe(()=>r.filter(be=>be.entityType==="visual").sort((be,Ee)=>be.name.localeCompare(Ee.name)),[r]),[Q,V]=P(()=>{try{return localStorage.getItem("codeyam-app-banner-dismissed")==="true"}catch{return!1}}),Y=ce(()=>{V(!0);try{localStorage.setItem("codeyam-app-banner-dismissed","true")}catch{}},[]),[B,H]=P(""),[ne,oe]=P(()=>new Set),Z=ye(null),re=ye(0),ue=ce(()=>{Z.current&&(re.current=Z.current.scrollTop)},[]);se(()=>{Z.current&&re.current>0&&(Z.current.scrollTop=re.current)});const we=(y==null?void 0:y.sha)??"overview";if(!e)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Ready to build something?"}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(w==="candidate")return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-5 px-8 text-center max-w-[420px]",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Migrate Your Project"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"It looks like you have an existing project. Claude can survey your codebase and systematically migrate it — deconstructing pages into clean components, extracting functions with tests, and creating scenarios. One page per session."}),n("button",{onClick:S,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Get Started"}),n("button",{onClick:h,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none p-0 cursor-pointer underline",children:"Skip — build a new feature instead"})]})});if(w==="active"&&C){const be=C.pages||[],Ee=be.filter(ae=>ae.status==="complete").length,X=be.length,fe=X>0?Math.round(Ee/X*100):0;return d("div",{className:"flex-1 flex flex-col overflow-auto p-4 font-['IBM_Plex_Sans']",children:[n("h2",{className:"text-lg font-medium text-white m-0 mb-3",children:"Project Migration"}),d("div",{className:"mb-4",children:[n("div",{className:"flex items-center gap-2 mb-1",children:d("span",{className:"text-xs text-gray-400",children:[Ee,"/",X," pages (",fe,"%)"]})}),n("div",{className:"w-full h-1.5 bg-[#2d2d2d] rounded-full overflow-hidden",children:n("div",{className:"h-full bg-[#005c75] rounded-full transition-all",style:{width:`${fe}%`}})})]}),n("div",{className:"space-y-1.5",children:be.map((ae,ie)=>{const he=ae.status==="complete"?"✓":ae.status==="in-progress"?"→":"○",Te=ae.status==="complete"?"text-green-400":ae.status==="in-progress"?"text-cyan-400":"text-gray-600";return d("div",{className:"flex items-center gap-2",children:[n("span",{className:`text-xs ${Te} w-3 text-center`,children:he}),n("span",{className:`text-xs ${ae.status==="in-progress"?"text-white font-medium":ae.status==="complete"?"text-gray-400":"text-gray-600"}`,children:ae.name}),n("span",{className:"text-[10px] text-gray-600",children:ae.route}),ae.status==="complete"&&d("span",{className:"text-[10px] text-gray-600",children:[(ae.extractedComponents||[]).length,"c"," ",(ae.extractedFunctions||[]).length,"f"," ",ae.scenarioCount||0,"s"]})]},ie)})}),(C.sharedComponents||[]).length>0&&d("div",{className:"mt-4",children:[n("h3",{className:"text-xs font-medium text-gray-400 mb-1.5",children:"Shared Components"}),(C.sharedComponents||[]).map((ae,ie)=>d("div",{className:"text-[10px] text-gray-500 mb-0.5",children:[ae.name," ",d("span",{className:"text-gray-600",children:["— used in: ",(ae.usedInPages||[]).join(", ")]})]},ie))]}),n("div",{className:"mt-4",children:n("button",{onClick:h,className:"px-4 py-2 bg-[#005c75] text-white text-xs font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Continue in Chat"})})]})}return t.length>0||K.length>0?y?n(qp,{focusedEntity:y,breadcrumbItems:k,onZoomChange:g,projectRoot:l,scenarios:t,analyzedEntities:r,activeScenarioId:c,onScenarioSelect:u,onAnalyzedScenarioSelect:p,onSwitchToBuild:h,entityImports:x,glossaryFunctions:o,cachedTestResults:a,glossaryEntries:i,entityShaMap:D,componentGroups:j,visualEntities:K,isEntityComplete:E,onReseedPreview:T}):U?n(nE,{onBack:()=>{W==null||W(!1),M==null||M(!0)}}):R?n(tE,{onBack:()=>{z==null||z(!1),M==null||M(!0)},onPreviewShowcase:()=>O==null?void 0:O()}):_&&$?n(K5,{onBack:()=>M==null?void 0:M(!1),onSwitchToBuild:h,onSwitchToHistory:m,onNavigateToDesignSystem:()=>{M==null||M(!1),z==null||z(!0)},onNavigateToTechStack:()=>{M==null||M(!1),W==null||W(!0)},expandedTasks:ne,onExpandedTasksChange:oe}):n("div",{ref:Z,onScroll:ue,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4 flex flex-col gap-12",children:[I.length>1&&n(f5,{brokenEntities:I}),!Q&&d("div",{className:"relative border border-[#2e7d32]/40 bg-cybg rounded-lg p-4 pr-10",children:[n("button",{onClick:Y,className:"absolute top-3 right-3 text-[#D7FF63] hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-sm text-white font-medium m-0 leading-snug",children:"These are all the pages in your project."}),d("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:["(1) Select a scenario below and switch to"," ",n("button",{type:"button",onClick:h,className:"underline text-[#D7FF63] bg-transparent border-none cursor-pointer p-0 text-sm inline hover:text-[#D7FF63]/70 transition-colors",children:"build"})," ","to change or enhance an existing page."]}),n("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:"(2) Select a page to see all of its sub-components and edit scenarios."})]}),_&&n("div",{className:"mb-4",children:n(T5,{onNavigateToRoadmap:()=>M==null?void 0:M(!0),onSwitchToBuild:h})}),J.size>0&&d("div",{children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider shrink-0",children:"Pages"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:B,onChange:be=>H(be.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),d("button",{onClick:h,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Page"]})]}),n("div",{className:"border-b border-[#2d2d2d] mt-3"}),[...J.entries()].sort(([be],[Ee])=>be==="Home"?-1:Ee==="Home"?1:be.localeCompare(Ee)).filter(([be])=>{if(!B.trim())return!0;const Ee=D.get(be);return((Ee?F.get(Ee):void 0)||be).toLowerCase().includes(B.trim().toLowerCase())}).map(([be,Ee])=>{const X=Ee.some(fe=>fe.id===c);return n("div",{className:"mt-2",children:D.has(be)&&E(D.get(be))?d(ve,{children:[n("div",{className:"flex items-center gap-1.5 py-1",children:d("button",{onClick:()=>g(be,D.get(be)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${X?"text-[#D7FF63]":"text-gray-300"}`,children:[(()=>{const fe=D.get(be);return(fe?F.get(fe):void 0)||be})(),d("span",{className:`font-normal text-sm ${X?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",Ee.length,")"]}),n("svg",{className:X?"text-[#D7FF63]/60":"text-gray-500",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})})]})}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:fn(Ee).map(({scenario:fe,dimensionLabel:ae,screenshotPath:ie,key:he})=>n(Us,{scenarioId:fe.id,screenshotPath:ie,updatedAt:fe.updatedAt,hasScreenshot:!!ie,name:fe.name,dimensionLabel:ae,isActive:fe.id===c,onSelect:()=>u(fe,ae??void 0)},he))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-sm font-normal text-gray-500",children:(()=>{const fe=D.get(be);return fe&&F.get(fe)||be})()}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),n("p",{className:"text-xs text-[#E0D400]/80 m-0 leading-relaxed",children:"Data missing for this page."}),n(Gp,{name:be,scenarios:Ee,reason:D.has(be)?"incomplete":"missing"})]})]})},be)})]})]})},we):n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[v?d(ve,{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:v}),N&&n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:N})]}):n("h2",{className:"text-lg font-medium text-white m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})})}const wd=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"history",label:"History"}],sE=()=>n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"text-[#8E8E8E] shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function oE({activeTab:e,onTabChange:t,buildIdle:r,projectTitle:s,breadcrumbItems:o,onBreadcrumbNavigate:a}){const[i,l]=P(!1),c=ye(null);se(()=>{if(!i)return;const p=h=>{c.current&&!c.current.contains(h.target)&&l(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[i]);const u=o&&o.length>0;return d("div",{className:"shrink-0 z-20 @container",children:[d("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:uo,alt:"CodeYam",className:"h-5 shrink-0"}),n("span",{className:"text-sm font-medium text-white whitespace-nowrap hidden @min-[500px]:inline",children:"CodeYam Editor"})]}),n("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n("div",{className:"hidden @min-[350px]:flex items-center gap-1",children:wd.map(p=>d("button",{onClick:()=>t(p.key),className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer border-b ${e===p.key?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent hover:text-white font-light"}`,children:[p.label,p.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},p.key))})]}),n("div",{className:"flex-1"}),n("button",{onClick:()=>t("settings"),className:`hidden @min-[350px]:block p-1.5 rounded-md transition-colors cursor-pointer ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white"}`,title:"Settings",children:d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"3"}),n("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),d("div",{className:"@min-[350px]:hidden relative",ref:c,children:[n("button",{onClick:()=>l(!i),className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Menu",children:d("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[n("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),n("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),n("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),i&&d("div",{className:"absolute right-0 top-full mt-1 bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[140px] z-50",children:[wd.map(p=>d("button",{onClick:()=>{t(p.key),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e===p.key?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:[p.label,p.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},p.key)),n("div",{className:"border-t border-[#3d3d3d] my-1"}),n("button",{onClick:()=>{t("settings"),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:"Settings"})]})]})]}),n("div",{className:`bg-[#161616] h-8 flex items-center px-4 border-b border-[#2d2d2d]${e==="build"?" hidden":""}`,children:n("nav",{className:"flex items-center gap-2 text-sm min-w-0",children:u?d(ve,{children:[n("button",{type:"button",onClick:()=>a==null?void 0:a(),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer shrink-0",children:s||"Untitled Project"}),o.slice(1).map((p,h)=>{const m=h===o.length-2;return d("span",{className:"flex items-center gap-2 min-w-0",children:[n(sE,{}),m?n("span",{className:"text-white truncate",children:p.name}):n("button",{type:"button",onClick:()=>a==null?void 0:a(p.componentName,p.entitySha),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer truncate",children:p.name})]},p.componentName||p.name)})]}):n("span",{className:"text-[#8E8E8E]",children:s||"Untitled Project"})})})]})}function aE({onMouseDown:e,onDoubleClick:t,isDragging:r}){return d("div",{className:"shrink-0 relative flex items-center justify-center cursor-col-resize group",style:{width:12},onMouseDown:e,onDoubleClick:t,children:[n("div",{className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:r?3:1,backgroundColor:r?"#3b82f6":"#3d3d3d",transition:"width 100ms, background-color 100ms"}}),!r&&n("div",{className:"absolute inset-0 bg-blue-500/0 group-hover:bg-blue-500/20 transition-colors pointer-events-none"}),d("div",{className:"relative z-10 flex flex-col gap-[3px] opacity-0 group-hover:opacity-100 transition-opacity",style:r?{opacity:1}:void 0,children:[n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"})]})]})}const Nd=300,Is=150;function iE(e){const[t,r]=P(null),[s,o]=P(!1),a=ye(0),i=ye(null);se(()=>{e.current&&r(Math.round(e.current.offsetWidth*.5))},[e]);const l=ce(()=>{var x;return((x=e.current)==null?void 0:x.offsetWidth)??(typeof window<"u"?window.innerWidth:1024)},[e]),c=ce(x=>{x.preventDefault(),o(!0)},[]),u=ce(()=>{r(Math.round(l()*.5))},[l]),p=ce(()=>{r(x=>(x&&x>0&&(i.current=x),0))},[]),h=ce(()=>{const x=i.current;i.current=null,r(x&&x>=Nd?x:Math.round(l()*.5))},[l]),m=ce(()=>{r(Math.round(l()*.5))},[l]);se(()=>{if(!s)return;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const x=v=>{cancelAnimationFrame(a.current),a.current=requestAnimationFrame(()=>{var _;const N=(_=e.current)==null?void 0:_.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,S=((N==null?void 0:N.width)??window.innerWidth)-Is,k=v.clientX-w,T=Math.min(Math.max(k,Nd),S);r(T)})},b=v=>{var k;cancelAnimationFrame(a.current),o(!1);const N=(k=e.current)==null?void 0:k.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,C=(N==null?void 0:N.width)??window.innerWidth,S=v.clientX-w;S<Is?r(0):C-S<Is&&r(C)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{cancelAnimationFrame(a.current),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b),document.body.style.cursor="",document.body.style.userSelect=""}},[s,e]),se(()=>{const x=()=>{r(b=>{if(b===null||b===0)return b;const v=l();return b>=v?v:Math.min(b,v-Is)})};if(!(typeof window>"u"))return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[l]);const f=l(),y=t===0,g=t!==null&&t>=f;return{editorWidth:t,isDragging:s,isEditorCollapsed:y,isPreviewCollapsed:g,handleMouseDown:c,handleDoubleClick:u,collapseEditor:p,expandEditor:h,expandPreview:m}}function lE({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:o,onLoadCommit:a}){const i=t*s,l=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${i}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg border-2 border-[#ccc] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${i}px`,maxHeight:`${l}px`},children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"block",style:{width:`${i}px`}})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666] shrink-0",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:e.commitSha&&a&&n(cE,{commitSha:e.commitSha,onLoadCommit:a})})]})}function cE({commitSha:e,onLoadCommit:t}){const[r,s]=P(!1),[o,a]=P(null);return d(ve,{children:[n("button",{onClick:()=>{s(!0),a(null),t(e).then(i=>{i.success||a(i.error||"Failed to load commit")}).catch(i=>{a(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Reverting...":"Revert to this code and load this version"}),o&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:o})]})}function dE({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:o}){const a=t*s,i=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${a}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-gray-200 m-0 font-['IBM_Plex_Sans']",children:e.scenarioName}),d("div",{className:"flex items-center justify-center gap-2 mt-2",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("p",{className:"text-sm text-amber-400/90 m-0 font-['IBM_Plex_Sans']",children:"The app is being edited - you can control the live preview when building is paused or complete."})]})]}),e.hasScreenshot?n("div",{className:"rounded-lg border-2 border-[#4d4d4d] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${a}px`,maxHeight:`${i}px`},children:n(ir,{scenarioId:e.scenarioId,screenshotPath:e.screenshotPath,updatedAt:e.updatedAt,alt:e.scenarioName,imgClassName:"block w-full",className:""})}):n("div",{className:"rounded-lg border-2 border-[#4d4d4d] bg-[#1a1a1a] flex items-center justify-center w-[400px] h-[300px]",children:n("span",{className:"text-sm text-gray-500",children:"No screenshot available"})}),n("button",{onClick:o,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none cursor-pointer transition-colors shrink-0",children:"Dismiss"})]})}function uE({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,onStateChange:a}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=Bn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,enabled:!0});return se(()=>{a(i,l||c)},[i,l,c,a]),null}function pE({onSaveToCurrent:e,onSaveAsNew:t,onDismiss:r,isSaving:s,scenarioName:o}){return d("div",{className:"flex items-center justify-between px-4 py-1.5 bg-emerald-900/60 border-b border-emerald-700/50 text-emerald-200 text-xs",children:[n("span",{className:"font-medium",children:o?d(ve,{children:["Data modified in “",o,"”."]}):"Data modified."}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:e,disabled:s,className:"px-2.5 py-0.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:s?"Saving...":"Save to Scenario"}),n("button",{onClick:t,disabled:s,className:"px-2.5 py-0.5 bg-emerald-800 hover:bg-emerald-700 disabled:opacity-50 text-emerald-200 text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:"Save as New"}),n("button",{onClick:r,disabled:s,className:"text-emerald-400 hover:text-emerald-200 disabled:opacity-50 transition-colors cursor-pointer disabled:cursor-not-allowed",title:"Dismiss",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})}function hE({latestVersion:e}){const[t,r]=P(!1);if(t)return null;const s=`npm install -g @codeyam/codeyam-cli@${e}`;return d("div",{className:"shrink-0 w-full bg-[#D7FF63] px-4 py-1.5 flex items-center text-xs text-black font-['IBM_Plex_Sans']",children:[d("div",{className:"flex-1 flex items-center justify-center gap-2",children:[n("span",{children:"An update to the codeyam editor is available."}),n("code",{className:"bg-[#2d2d2d] text-white font-mono text-xs px-3 py-0.5 rounded-full",children:s}),n(xt,{content:s,icon:!0,iconSize:12,className:"text-black hover:text-gray-700 transition-colors"})]}),n("button",{type:"button",onClick:()=>r(!0),className:"shrink-0 p-0.5 rounded text-black/60 hover:text-black hover:bg-black/10 transition-colors cursor-pointer bg-transparent border-none","aria-label":"Dismiss upgrade banner",children:n("svg",{className:"w-3.5 h-3.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 mE(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function fE(e){const[t,r]=P({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),s=ye(t);s.current=t,se(()=>{let i=!1,l=null;const c=async()=>{try{const u=await fetch("/api/editor-dev-server");if(i)return;const p=await u.json(),h=mE(s.current,p),{shouldAutoStart:m,...f}=h;if(r(f),m&&!(e!=null&&e.skipAutoStart))try{const y=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(i)return;y.ok?r(g=>({...g,isStarting:!0})):r(g=>({...g,canStartServer:!1}))}catch{}}catch{}};return c(),l=setInterval(()=>void c(),2e3),()=>{i=!0,l&&clearInterval(l)}},[t.url]);const o=ce(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),a=ce(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:t.url,proxyUrl:t.proxyUrl,isStarting:t.isStarting,error:t.error,canStartServer:t.canStartServer,retryServer:o,startServer:a}}function gE(e){const t=ye(null),r=ye(null);se(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s)return;if(t.current||(t.current=s.href),!e){s.href=t.current;return}const o=new Image;o.crossOrigin="anonymous",o.onload=()=>{const a=r.current,i=a.getContext("2d");i.clearRect(0,0,64,64);const l=56,c=(64-l)/2;i.drawImage(o,c,c,l,l);const u=12,p=64-u-1,h=u+1;i.beginPath(),i.arc(p,h,u,0,2*Math.PI),i.fillStyle="#ef4444",i.fill(),s.href=a.toDataURL("image/png")},o.src=t.current},[e]),se(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}function yE(e){if(!e||typeof e!="object")return[];for(const t of Object.values(e))if(Array.isArray(t))return t;return[]}function xE(e){return G.join(e,".codeyam","migration-state.json")}function Zp(e){const t=xE(e);try{const r=q.readFileSync(t,"utf8"),s=JSON.parse(r);return bE(s)}catch{return null}}function bE(e){const t=Array.isArray(e.pages)?e.pages:[],r=Array.isArray(e.sharedComponents)?e.sharedComponents:[];return{status:e.status||"surveyed",startedAt:e.startedAt||new Date().toISOString(),completedAt:e.completedAt??null,currentPageIndex:typeof e.currentPageIndex=="number"?e.currentPageIndex:0,pages:t.map(s=>({name:s.name||"Unknown",route:s.route||"/",filePath:s.filePath||"",status:s.status||"pending",startedAt:s.startedAt??null,completedAt:s.completedAt??null,extractedComponents:Array.isArray(s.extractedComponents)?s.extractedComponents:[],extractedFunctions:Array.isArray(s.extractedFunctions)?s.extractedFunctions:[],scenarioCount:typeof s.scenarioCount=="number"?s.scenarioCount:0})),sharedComponents:r.map(s=>({name:s.name||"",filePath:s.filePath||"",extractedFromPage:s.extractedFromPage||"",usedInPages:Array.isArray(s.usedInPages)?s.usedInPages:[]}))}}function vE(e,t){if(!q.existsSync(G.join(e,"package.json"))||t!=null&&t.hasEditorScenarios)return!1;const r=G.join(e,".codeyam","glossary.json");if(q.existsSync(r))try{const a=JSON.parse(q.readFileSync(r,"utf8"));if((Array.isArray(a)?a:yE(a)).length>0)return!1}catch{}const s=G.join(e,".codeyam","editor-step.json");if(q.existsSync(s))try{const a=JSON.parse(q.readFileSync(s,"utf8"));if(a.feature||a.scaffolded)return!1}catch{}const o=Zp(e);return(o==null?void 0:o.status)!=="complete"}function wE(e){const t=G.join(e,".codeyam","editor-step.json");try{const r=q.readFileSync(t,"utf8");return!!JSON.parse(r).migration}catch{return!1}}function NE({currentUrl:e,nextUrl:t,formMethod:r,defaultShouldRevalidate:s}){return r||e.pathname===t.pathname?s:e.pathname.startsWith("/editor")&&t.pathname.startsWith("/editor")?!1:s}const SE=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];function CE(e){const t=new URL(e).pathname.match(/\/editor\/entity\/([^/]+)/);return t?t[1]:null}async function kE({request:e}){var E;const t=await Ye();let r=!1,s=[],o=[];const a=Ce()||process.cwd();let i={map:{},allFiles:[]};try{i=Mi(a)}catch{}let l=[];try{l=gr()}catch{}if(t){const{project:F}=await De(t);r=((E=F.metadata)==null?void 0:E.editorMode)??!1;try{const I=$e();try{const Y=await I.selectFrom("editor_scenarios").select(["id","url"]).where("project_id","=",F.id).where("component_name","is",null).where("page_file_path","is",null).execute();if(Y.length>0){const{allFiles:B}=i;for(const H of Y){const ne=H;if(!ne.url)continue;const oe=gu(ne.url,B);oe&&await I.updateTable("editor_scenarios").set({page_file_path:oe}).where("id","=",ne.id).execute()}}}catch(Y){console.warn("[editor] page_file_path backfill failed (non-fatal):",Y instanceof Error?Y.message:Y)}const K=await I.selectFrom("editor_scenarios").selectAll().where("project_id","=",F.id).orderBy("created_at","asc").execute(),Q=Y=>{const B=Y;let H=null,ne=null;try{B.dimensions&&(H=typeof B.dimensions=="string"?JSON.parse(B.dimensions):B.dimensions)}catch{}try{B.screenshot_paths&&(ne=typeof B.screenshot_paths=="string"?JSON.parse(B.screenshot_paths):B.screenshot_paths)}catch{}return{id:Y.id,name:Y.name,description:Y.description||"",componentName:Y.component_name||null,componentPath:Y.component_path||null,screenshotPath:Y.screenshot_path||null,url:B.url||null,type:B.type||null,viewportWidth:B.viewport_width||null,viewportHeight:B.viewport_height||null,dimensions:H,screenshotPaths:ne,pageFilePath:B.page_file_path||null,entitySha:B.entity_sha||null,displayName:B.display_name||null,updatedAt:B.updated_at||null}};o=Tt(K,Y=>`${Y.name}::${Y.url||"/"}`).map(Q);const V=Gu(a);if(V){const Y=Xr(V),B=K.filter(H=>xi(H,Y));s=Tt(B,H=>`${H.name}::${H.url||"/"}`).map(Q)}else s=o}catch{}}const c=[...new Set(o.map(F=>F.componentName).filter(F=>F!==null))];let u=[];try{const F=G.join(a,".codeyam","glossary.json");if(q.existsSync(F)){const I=q.readFileSync(F,"utf8");u=JSON.parse(I)}}catch{}const p=Ey(u),h={};try{const F=Li(a),I=p.filter(K=>K.testFile).map(K=>({filePath:K.filePath,testFile:K.testFile}));if(I.length>0){const K=zi(a,I);for(const[Q,V]of Object.entries(F.results)){const Y=K[Q];h[Q]={...V,stale:Y?lp(V,Y.sourceHash,Y.testHash):!0}}}}catch{}let m=[],f=[];try{const F=await zn()||[];m=F.map(I=>({sha:I.sha,name:I.name,entityType:I.entityType||"visual",filePath:I.filePath||""})),f=_y(F,u)}catch{}let y=[];try{if(m.length>0){const F=m.map(I=>I.sha);await We(),y=await tt({shas:F})||[]}}catch{}let g={};try{if(y.length>0){const F=new Set([...f.map(I=>I.name),...m.map(I=>I.name),...c,...u.map(I=>I.name)]);g=jy(y,F)}}catch{}const x=i.map,b=i.allFiles;if(Object.keys(x).length>0&&y.length>0&&(g=Py(g,x,y)),b.length>0&&y.length>0){const F=new Map;for(const I of y)I.filePath&&F.set(I.filePath,I.name);for(const I of b){const K=Ut($t(I));if(g[K])continue;const Q=F.get(I);Q&&g[Q]&&(g[K]=g[Q])}}let v={};try{v=(await yr({projectRoot:a,scenarioInputs:o,glossaryInputs:p,precomputedPageFilePaths:i,precomputedGitFiles:l,precomputedEntities:y})).entityChangeStatus}catch{}const N=l.filter(F=>F.status!=="deleted").map(F=>({path:F.path,status:F.status})),w=$o(a),C=Ri(a),S=$i(a),k=qu(a);let T=null,_=null,$=null,M=null,R=null,z=null,O=null;try{const F=G.join(a,".codeyam","config.json");if(q.existsSync(F)){const I=JSON.parse(q.readFileSync(F,"utf8"));T=I.projectTitle||null,_=I.projectDescription||null,$=I.defaultScreenSize||null,M=I.screenSizes||null,R=I.appFormats||null,z=I.provider||"claude";const K=I.handoff;K!=null&&K.lastProvider&&K.lastProvider!==z&&(O={from:K.lastProvider,to:z,lastStep:K.lastStep??null,lastStepLabel:(S==null?void 0:S.label)??null,handoffSummary:K.summary??null})}}catch{}R||(R=Fi(a));const U=CE(e.url);let W=null,J=null;if(U&&t)try{await We();const F=await tt({}),I=F==null?void 0:F.find(K=>K.sha===U);if(I){const K=I.name,Q=I.filePath||"",V=I.entityType||"visual";J={name:K,filePath:Q,entityType:V,displayName:K};const Y=F==null?void 0:F.find(B=>B.name===I.name&&B.filePath===I.filePath&&B.sha!==U&&B.createdAt&&I.createdAt&&B.createdAt>I.createdAt);Y&&(W=Y.sha)}}catch{}const j=Qu(a),D=j&&o.some(F=>F.id===j)?j:null;let A="none",L=null;try{if(L=Zp(projRoot),(L==null?void 0:L.status)==="complete")A="complete";else if((L==null?void 0:L.status)==="in-progress"||(L==null?void 0:L.status)==="surveyed")A="active";else if(wE(projRoot))A="active";else if(t){const F=o.length>0;vE(projRoot,{hasEditorScenarios:F})&&(A="candidate")}}catch{}return le({projectSlug:t,projectRoot:Ce(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:o,components:c,analyzedEntities:f,allEntities:m,glossaryFunctions:p,glossaryEntries:u,entityImports:g,pageFilePaths:x,entityChangeStatus:v,modifiedFiles:N,featureName:w,userPrompt:C,projectTitle:T,projectDescription:_,defaultScreenSize:$,screenSizes:M,appFormats:R,editorStep:(S==null?void 0:S.step)??null,editorStepLabel:(S==null?void 0:S.label)??null,claudeSessionId:k,focusedEntitySha:U,newerEntitySha:W,focusedEntity:J,savedActiveScenarioId:D,migrationMode:A,migrationState:L,cachedTestResults:h,providerSwitch:O,currentProvider:z})}class EE extends zh{constructor(){super(...arguments);vt(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:d("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&d("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const _E=nt(function(){var Cl,kl;const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:o,allScenarios:a,analyzedEntities:i,allEntities:l,glossaryFunctions:c,glossaryEntries:u,entityImports:p,pageFilePaths:h,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g,projectTitle:x,projectDescription:b,defaultScreenSize:v,screenSizes:N,appFormats:w,editorStep:C,editorStepLabel:S,claudeSessionId:k,focusedEntitySha:T,newerEntitySha:_,focusedEntity:$,migrationMode:M,migrationState:R,cachedTestResults:z,providerSwitch:O,currentProvider:U}=lt(),W=Cd("root"),J=(W==null?void 0:W.npmUpdate)??null,j=(W==null?void 0:W.isAdmin)??!1,[D,A]=lr(),L=zt(),E=ye(null),F=ye(null),I=ye(null),K=ye(null),[Q,V]=P(T),[Y,B]=P(!1),[H,ne]=P(!1),[oe,Z]=P(!1),[re,ue]=P(0);se(()=>{V(T)},[T]),se(()=>{const te=me=>{const Se=me.target;(Se.tagName==="BUTTON"||Se.closest("button"))&&(Se.closest("button")??Se).blur()};return document.addEventListener("mouseup",te),()=>document.removeEventListener("mouseup",te)},[]);const we=pe(()=>Xc(Q,l),[Q,l,a]),je=(we==null?void 0:we.displayName)??void 0,be=D.get("scenario")||((Cl=Ss(a))==null?void 0:Cl.id)||void 0,[Ee,X]=P(()=>je?[je]:[]),fe=ye(null),ae=ye([]),ie=ye(null);se(()=>{var Ue;const te=be||((Ue=Ss(a))==null?void 0:Ue.id);if(!zy(te,fe.current))return;const me=a.find(Qe=>Qe.id===te);if(!me)return;fe.current=te;const Se=la(me,ae.current,ie.current);Se&&Jt(Se);const Re=Dt(me.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Re,scenarioId:me.id,scenarioName:me.name,scenarioType:me.type})}).catch(()=>{})},[be,a]),se(()=>{const te=new BroadcastChannel("codeyam-editor");return te.onmessage=me=>{var Se;if(((Se=me.data)==null?void 0:Se.type)==="switch-scenario"&&me.data.scenarioId){const Re=me.data.scenarioId,Ue=a.find(Qn=>Qn.id===Re);if(!Ue)return;fe.current=Re;const Qe=new URLSearchParams(D);Qe.set("scenario",Re),Qe.delete("zoom"),A(Qe),Wt(null),nn(null),Ft(null),ln(!0);const cn=Dt(Ue.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:cn,scenarioId:Re,scenarioType:Ue.type})}).then(()=>{pt(!1),Hn(Qn=>Qn+1)}).catch(()=>{ln(!1)})}},()=>te.close()},[D,A,a]),se(()=>{if(D.get("ref")!=="link"||!be)return;const te=new BroadcastChannel("codeyam-editor");te.postMessage({type:"switch-scenario",scenarioId:be}),te.close(),window.close()},[]);const{devServerUrl:he,proxyUrl:Te,isStarting:xe,error:Oe,canStartServer:Je,retryServer:bt,startServer:Ge}=fE({skipAutoStart:M==="candidate"||M==="active"}),[xr,pt]=P(!1),[qe,Wt]=P(null),[br,nn]=P(null),[vr,Yn]=P(!1),[Un,Ft]=P(null),[ht,mt]=P(null),ft=ce(async te=>{const Se=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:te})})).json();return Se.success&&(Ft(null),pt(!1)),Se},[]),ct=ce((te,me)=>{nn(Se=>(te&&te!==Se&&pt(!1),te)),!me&&te&&pt(!0),Yn(me)},[]),wr=ce(te=>{Ft(null),Wt(Se=>(Se&&Se.analysisId===te.analysisId||(nn(null),Hn(Ue=>Ue+1)),te)),Yn(!0),pt(!1);const me=new URLSearchParams(D);me.delete("scenario"),me.delete("zoom"),A(me)},[D,A]),[Le,Jt]=P(v?{name:v.name,width:v.width,height:v.height}:{name:"Desktop",width:1440,height:900}),[ts,Nr]=P(!1),[dt,Sr]=P(!1),ns=(w==null?void 0:w.includes("mobile-app"))??!1,rs=v?{name:v.name,width:v.width,height:v.height}:null;ie.current=rs;const ss=Vr(),Xe=pe(()=>{const te=ss.pathname.split("/").filter(Boolean),me=te[te.length-1];return me==="build"||me==="history"||me==="settings"?me:me==="structure"?"data":"app"},[ss.pathname]),gt=ce(te=>{V(null),X([]),B(!1);const me=te==="app"?"":`/${te==="data"?"structure":te}`,Se=D.get("scenario"),Re=Se?`?scenario=${Se}`:"";L(`/editor${me}${Re}`)},[L,D]),Cr=ce(()=>{gt("build"),rn(!0)},[gt]),Oo=ce(()=>{gt("history")},[gt]),Lo=ce(()=>{gt("build"),rn(!0),setTimeout(()=>{var te;(te=E.current)==null||te.sendInput("codeyam editor migrate")},300)},[gt]),[kr,rn]=P(Xe==="build"),sn=!!(y&&C),on=C!=null&&C<=1,[Ht,vn]=P(O&&sn&&!on?"provider-switch":sn&&!on?"pending":sn&&on?"fresh":"no-session"),Er=ye(!1);se(()=>{(Ht==="pending"||Ht==="provider-switch")&&!Er.current&&(Er.current=!0,gt("build"),rn(!0))},[Ht,gt]);const _r=ye(!1);se(()=>{sn&&on&&!_r.current&&(_r.current=!0,fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}))},[sn,on]);const os=ce(()=>{vn("continue")},[]),as=ce(()=>{fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),vn("fresh")},[]),is=ce(async()=>{await fetch("/api/editor-handoff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"accept"})}).catch(()=>{}),await fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear-session-id"})}).catch(()=>{}),vn("fresh")},[]),ls=ce(async()=>{await fetch("/api/editor-handoff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"dismiss"})}).catch(()=>{}),await fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),vn("fresh")},[]),[cs,Wn]=P("none"),ds=ce(()=>{Wn("choosing")},[]),us=ce(()=>{var te;fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Wn("none"),(te=E.current)==null||te.sendInput("/clear"),setTimeout(()=>{var me;(me=E.current)==null||me.sendInput("/codeyam-editor")},500)},[]),ps=ce(()=>{Wn("none")},[]),[ge,Fe]=P(!1),[rt,ze]=P(!1),ot=ye(!1),yt=ye(0),He=ye(!1),at=ce(te=>{Fe(te),te||(He.current=!0),te&&!ot.current&&(ze(!1),yt.current=Date.now()),te||(yt.current=0),ot.current=te},[]),[Ve,wn]=P(!1),Nn=ye(!1),Xp=ce(te=>{te!==Nn.current&&(console.log("[Editor] claudeBuilding: %s → %s",Nn.current,te),Nn.current=te,wn(te))},[]);gE(ge);const sl=ye(Ve);se(()=>{var me;const te=sl.current&&!Ve;if(sl.current=Ve,!Ve)if(te){const Se=D.get("scenario")||((me=Ss(a))==null?void 0:me.id),Re=a.find(Ue=>Ue.id===Se);if(Re){console.log("[Editor] Building stopped, loading live preview for: %s",Re.name),mt(null);const Ue=Dt(Re.name);fe.current=Re.id,ln(!0),Vn(!1),pt(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ue,scenarioId:Re.id,scenarioType:Re.type,skipBroadcast:!0})}).then(()=>{Hn(Qe=>Qe+1)}).catch(()=>{ln(!1),pt(!0)})}else mt(null)}else mt(null)},[Ve,D,a]);const{editorWidth:ol,isDragging:al,isEditorCollapsed:Sn,isPreviewCollapsed:zo,handleMouseDown:eh,handleDoubleClick:th,collapseEditor:nh,expandEditor:il,expandPreview:rh}=iE(K),[Bo,ll]=P(!1),sh=ce(()=>{ll(!0),gt("build"),rn(!0)},[gt]),cl=ce(()=>{ll(!1)},[]),oh=ce(te=>{Jt(te),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:te,skipBroadcast:!0})})},[]),[dl,ul]=P(tr);se(()=>{const te=py();ul(te),te.systemNotification&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]);const ah=ce(te=>{ul(te),hy(te)},[]);se(()=>{if(Xe==="build"){Fe(!1);const te=setTimeout(()=>{var me,Se;(me=E.current)==null||me.scrollToBottom(),(Se=E.current)==null||Se.focus()},50);return()=>clearTimeout(te)}},[Xe]),se(()=>{function te(){!document.hidden&&Xe==="build"&&Fe(!1)}return document.addEventListener("visibilitychange",te),()=>document.removeEventListener("visibilitychange",te)},[Xe]);const[Cn,ih]=P(null);se(()=>{const te=I.current;if(!te)return;const me=new ResizeObserver(Se=>{const Re=Se[0];Re&&ih({width:Re.contentRect.width,height:Re.contentRect.height})});return me.observe(te),()=>me.disconnect()},[]);const jr=ns&&!dt&&(Le.height??900)>Le.width,an=pe(()=>Cn?jr?Zl(Cn,{width:Le.width+$s.width,height:(Le.height??900)+$s.height}):Zl(Cn,Le):1,[Cn,Le,jr]),[Jn,Hn]=P(0),[pl,Yo]=P(null),[hs,ln]=P(!1),ms=ye(!1),[lh,Vn]=P(!1),[ch,hl]=P(!1),Uo=ye(0);se(()=>{Jn>0&&(Uo.current=Date.now()+3e3)},[Jn]);const dh=ce(()=>{if(Date.now()<Uo.current)return;const te=yt.current;te===0||Date.now()-te<5e3||Vn(!0)},[]);se(()=>{const te=me=>{var Se;if(((Se=me.data)==null?void 0:Se.type)==="codeyam-localstorage-changed"){if(Date.now()<Uo.current)return;const Re=yt.current;if(Re===0||Date.now()-Re<5e3)return;Vn(!0)}};return window.addEventListener("message",te),()=>window.removeEventListener("message",te)},[]);const ml=ce(async te=>{hl(!0);try{let me;const Se=F.current;Se!=null&&Se.contentWindow&&(me=await new Promise(Qe=>{const cn=setTimeout(()=>Qe(void 0),2e3),Qn=El=>{var _l;((_l=El.data)==null?void 0:_l.type)==="codeyam-localstorage-state"&&(clearTimeout(cn),window.removeEventListener("message",Qn),Qe(El.data.data))};window.addEventListener("message",Qn),Se.contentWindow.postMessage({type:"codeyam-get-localstorage"},"*")}));const Ue=await(await fetch("/api/editor-save-seed-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:te,localStorage:me})})).json();Ue.success?Vn(!1):console.error("[editor] Save seed state failed:",Ue.error)}catch(me){console.error("[editor] Save seed state error:",me)}finally{hl(!1)}},[]),uh=ce((te,me)=>{if(Yo(te||null),me){const Se=new URLSearchParams(D);Se.set("scenario",me),fe.current=me,A(Se);const Re=a.find(Ue=>Ue.id===me);if(Re){const Ue=la(Re,ae.current,ie.current);Ue&&Jt(Ue)}}Ft(null),pt(!1),Hn(Se=>Se+1)},[D,A,a]),{customSizes:Wo,addCustomSize:ph,removeCustomSize:hh}=No(t),Pr=pe(()=>Up(N,w),[N,w]),fs=pe(()=>[...Pr,...Wo],[Pr,Wo]);ae.current=fs;const gs=pe(()=>{const te=new Map;for(const me of l){te.set(me.name,me.sha);const Se=Ut($t(me.filePath));Se!==me.name&&te.set(Se,me.sha)}return te},[l]),fl=pe(()=>{const te=new Map;for(const me of l)te.set(me.sha,me.name);return te},[l]),gl=pe(()=>{const te=[{name:"App"}];Y&&te.push({name:"Roadmap"}),H&&te.push({name:"Design System"}),oe&&te.push({name:"Tech Stack"});for(const me of Ee){const Se=gs.get(me),Re=Se?fl.get(Se):void 0;te.push({name:Re||me,componentName:me,entitySha:Se})}return te},[Ee,gs,fl,Y,H,oe]),{pageGroups:yl,componentGroups:Jo}=pe(()=>nl(a),[a]),ys=pe(()=>Hp(yl,Jo),[yl,Jo]),[mh,fh]=P("application"),[Kn,Ho]=P([]),[Vo,xl]=P(null),bl=pe(()=>Vo?Xc(Vo,l):null,[Vo,l,a]),vl=pe(()=>{const te=[{name:"App"}];for(const me of Kn)te.push({name:me,componentName:me,entitySha:gs.get(me)});return te},[Kn,gs]),Ko=ce((te,me)=>{if(!te){Ho([]),xl(null);return}const Se=me||ys.get(te);if(!Se)return;const Re=Kn.indexOf(te);Re>=0?Ho(Kn.slice(0,Re+1)):Ho([...Kn,te]),xl(Se)},[Kn,ys]),wl=ce((te,me)=>{if(!te){X([]),V(null);const Qe=D.get("scenario"),cn=Qe?`?scenario=${Qe}`:"";L(`/editor${cn}`);return}if(!me){console.error(`[editor] No entity SHA for "${te}" — entity missing from database`);return}const Se=Ee.indexOf(te);Se>=0?X(Ee.slice(0,Se+1)):X([...Ee,te]);const Re=a.find(Qe=>Qe.entitySha===me);V(me);const Ue=Re?`?scenario=${Re.id}`:"";L(`/editor/entity/${me}${Ue}`)},[L,a,Ee,D]),Nl=ce(te=>{ln(!0),ms.current=!0,Vn(!1),pt(!1);const me=Dt(te.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:me,scenarioId:te.id,scenarioType:te.type,skipBroadcast:!0})}).then(()=>{ms.current=!1,Hn(Se=>Se+1)}).catch(()=>{ms.current=!1,ln(!1),pt(!0)})},[]),Gn=ce((te,me)=>{console.log("[Editor] Scenario selected: %s dimension=%s (claudeBuilding=%s)",te.name,me??"default",Ve),Wt(null),nn(null),Ft(null),Yo(null);let Se=null;if(me&&(N!=null&&N[me])){const Ue=N[me],Qe=fs.find(cn=>cn.width===Ue.width&&cn.height===Ue.height);Se={name:(Qe==null?void 0:Qe.name)||me,...Ue}}Se||(Se=la(te,fs,rs)),Se&&Jt(Se),fe.current=te.id;const Re=new URLSearchParams(D);Re.set("scenario",te.id),A(Re),Ve?mt({scenarioId:te.id,scenarioName:te.name,updatedAt:te.updatedAt,hasScreenshot:!!te.screenshotPath,screenshotPath:te.screenshotPath}):(mt(null),Nl(te))},[D,A,fs,N,Ve,Nl]),gh=ce(()=>{const te=be;if(!te)return;const me=a.find(Re=>Re.id===te);if(!me)return;const Se=Dt(me.name);pt(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Se,scenarioId:me.id,scenarioType:me.type})}).then(()=>{Hn(Re=>Re+1)})},[be,a]),yh=ce(te=>{if(!te.commitSha){const me=a.find(Se=>Se.name===te.scenarioName);if(me){Gn(me);return}}Ft(te)},[a,Gn]),xh=te=>{const me={name:te.name,width:te.width,height:te.height};Jt(me),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:me,skipBroadcast:!0})})},bh=(te,me,Se)=>{ph(te,me,Se)},vh=te=>{Jt(te),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:te,skipBroadcast:!0})})};se(()=>{const te=me=>{var Se;if(((Se=me.data)==null?void 0:Se.type)==="codeyam-preview-ready"&&!qe){if(ms.current)return;pt(!0),ln(!1)}};return window.addEventListener("message",te),()=>window.removeEventListener("message",te)},[qe]);const Sl=()=>{qe||setTimeout(()=>{pt(te=>(te||ln(!1),!0))},5e3)},qn=pe(()=>Ly({activeAnalyzedScenario:!!qe,analyzedPreviewUrl:br,activeScenarioId:be||null,scenarios:a,proxyUrl:Te,devServerUrl:he,zoomComponent:je||null}),[Te,he,je,be,a,qe,br]),Go=pe(()=>{if(H)return`/api/design-system-showcase?__cb=${re}`;const te=Nu(qn,pl);if(!te)return null;const me=te.includes("?")?"&":"?";return`${te}${me}__cb=${Jn}`},[qn,pl,Jn,H,re]),wh=pe(()=>({projectSlug:t,hasProject:s,scenarioCount:o==null?void 0:o.length,allScenarioCount:a==null?void 0:a.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:c==null?void 0:c.length,entityChangeStatusKeys:m?Object.keys(m):[],featureName:y}),[t,s,o,a,i,c,m,y]);return d(ve,{children:[n(EE,{loaderSnapshot:wh,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[qe&&n(uE,{analysisId:qe.analysisId,scenarioId:qe.scenarioId,scenarioName:qe.scenarioName,entityName:qe.entityName,projectSlug:t,onStateChange:ct},qe.analysisId),J&&n(hE,{latestVersion:J.latestVersion}),d("div",{ref:K,className:"flex-1 flex min-h-0",children:[Sn&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:il,title:"Expand editor",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M1 1l4 4-4 4"})})}),d("aside",{className:"bg-[#1e1e1e] shrink-0 flex flex-col overflow-hidden",style:{...Sn?{display:"none"}:ol!==null?{width:`${ol}px`}:{width:"50%"}},children:[_&&we&&d("div",{className:"px-3 py-2 text-xs flex items-center justify-between",style:{background:"#2a1f00",borderBottom:"1px solid #3d2e00",color:"#f0c040"},children:[d("span",{children:["Viewing an older version of"," ",n("strong",{children:we.name}),". A newer version exists."]}),n("a",{href:`/editor/entity/${_}`,className:"px-2 py-0.5 rounded text-xs",style:{background:"#3d2e00",color:"#f0c040",textDecoration:"none"},children:"View latest"})]}),n(oE,{activeTab:Xe,onTabChange:te=>{gt(te),te==="build"&&rn(!0),fetch("/api/telemetry-page-view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({route:`/editor/${te}`})}).catch(()=>{})},buildIdle:ge,projectTitle:x,breadcrumbItems:Xe==="data"?vl:gl,onBreadcrumbNavigate:Xe==="data"?Ko:wl}),d("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[ge&&Xe!=="build"&&!rt&&d("div",{className:"absolute top-3 left-1/2 -translate-x-1/2 z-50 animate-[slideDown_0.3s_ease-out]",children:[n("style",{children:`
|
|
756
|
+
@keyframes slideDown {
|
|
757
|
+
from { transform: translate(-50%, -100%); opacity: 0; }
|
|
758
|
+
to { transform: translate(-50%, 0); opacity: 1; }
|
|
759
|
+
}
|
|
760
|
+
`}),d("div",{className:"flex items-center gap-1 bg-amber-50 border-2 border-amber-300 rounded-lg shadow-lg",children:[d("button",{onClick:()=>{gt("build"),rn(!0)},className:"flex items-center gap-2 px-4 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-l-md",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("span",{className:"text-sm font-medium text-amber-900",children:"Claude is waiting for you"}),n("span",{className:"text-xs text-amber-600 ml-1",children:"Go to Build"})]}),n("button",{onClick:te=>{te.stopPropagation(),ze(!0)},className:"px-2 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-r-md text-amber-400 hover:text-amber-600","aria-label":"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M3 3l8 8M11 3l-8 8"})})})]})]}),kr&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Xe==="build"?"visible":"hidden"},children:[n(n5,{projectTitle:x,featureName:y,editorStep:C,editorStepLabel:S,migrationMode:M}),n("div",{className:"flex-1 min-h-0",style:Bo?{flex:"1 1 50%"}:void 0,children:Ht==="provider-switch"&&O?n(Vk,{from:O.from,to:O.to,lastStep:O.lastStep,lastStepLabel:O.lastStepLabel,handoffSummary:O.handoffSummary,featureName:y,onContinue:()=>void is(),onStartFresh:()=>void ls()}):Ht==="pending"?n(Kk,{featureName:y,editorStep:C,editorStepLabel:S,onContinue:os,onStartFresh:as}):d("div",{className:"relative h-full",children:[n(fu,{ref:E,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:uh,onShowResults:sh,onHideResults:cl,onSetViewport:oh,onDataMutationForwarded:dh,onFeatureComplete:ds,editorMode:!0,onIdleChange:at,onBuildingChange:Xp,notificationSettings:dl,buildTabActive:Xe==="build",claudeStartMode:Ht==="continue"?"resume":"fresh",claudeSessionId:k,editorStepLabel:S,resultsOpen:Bo}),cs==="choosing"&&n(Gk,{onStartNextFeature:us,onContinueInSession:ps})]})}),Bo&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(m5,{scenarios:o,allScenarios:a,glossaryFunctions:c,cachedTestResults:z,projectRoot:r,activeScenarioId:be,onScenarioSelect:Gn,onClose:cl,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Xe==="app"?"visible":"hidden"},children:n(rE,{hasProject:s,scenarios:a,analyzedEntities:i,allEntities:l,glossaryFunctions:c,cachedTestResults:z,glossaryEntries:u,projectRoot:r,activeScenarioId:be,onScenarioSelect:Gn,onAnalyzedScenarioSelect:wr,onSwitchToBuild:Cr,onSwitchToHistory:Oo,zoomComponent:je,focusedEntity:we,onZoomChange:wl,entityImports:p,pageFilePaths:h,projectTitle:x,projectDescription:b,breadcrumbItems:gl,migrationMode:M,migrationState:R,onStartMigration:Lo,onReseedPreview:gh,isAdmin:j,roadmapView:Y,onRoadmapViewChange:B,designSystemView:H,onDesignSystemViewChange:ne,onPreviewDesignSystem:()=>{ue(te=>te+1)},techStackView:oe,onTechStackViewChange:Z})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Xe==="data"?"visible":"hidden"},children:bl?n(qp,{focusedEntity:bl,breadcrumbItems:vl,onZoomChange:Ko,projectRoot:r,scenarios:a,analyzedEntities:[],activeScenarioId:be,onScenarioSelect:Gn,onAnalyzedScenarioSelect:wr,onSwitchToBuild:Cr,entityImports:p,glossaryFunctions:c,cachedTestResults:z,glossaryEntries:u,entityShaMap:ys,componentGroups:Jo,visualEntities:[],isEntityComplete:()=>!0}):n(r5,{scenarios:a,projectRoot:r,activeScenarioId:be,onScenarioSelect:Gn,zoomComponent:void 0,focusedEntity:null,onZoomChange:Ko,analyzedEntities:[],glossaryFunctions:c,cachedTestResults:z,activeAnalyzedScenarioId:qe==null?void 0:qe.scenarioId,onAnalyzedScenarioSelect:wr,entityImports:p,pageFilePaths:h,onSwitchToBuild:Cr,entityShaMap:ys,structureTab:mh,onStructureTabChange:fh})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Xe==="history"?"visible":"hidden"},children:n(P5,{isActive:Xe==="history",onScreenshotClick:yh,glossaryFunctions:c,cachedTestResults:z})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Xe==="settings"?"visible":"hidden"},children:d("div",{className:"flex-1 overflow-auto p-4",children:[n("h2",{className:"text-sm font-semibold text-white mb-4",children:"Settings"}),n("p",{className:"text-xs text-gray-400",children:"Settings panel coming soon."})]})})]}),n(mu,{serverUrl:he,isStarting:xe,projectSlug:t,devServerError:Oe,onStartServer:Je?Ge:void 0,notificationSettings:dl,onChangeNotificationSettings:ah})]}),!Sn&&!zo&&n(aE,{onMouseDown:eh,onDoubleClick:th,isDragging:al}),zo&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:rh,title:"Expand preview",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M5 1l-4 4 4 4"})})}),d("div",{className:"flex-1 flex flex-col min-w-0",style:{...zo?{display:"none"}:void 0,...al?{pointerEvents:"none"}:void 0},children:[d("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center pr-4 relative",children:[n("div",{className:"flex items-center gap-1 shrink-0 z-10",children:n("button",{onClick:()=>{Sn?(il(),setTimeout(()=>{var te;return(te=E.current)==null?void 0:te.focus()},50)):nh()},className:`p-1.5 rounded transition-colors cursor-pointer ${Sn?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:Sn?"Show chat":"Hide chat",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:Sn?d(ve,{children:[n("path",{d:"M13 17l5-5-5-5"}),n("path",{d:"M6 17l5-5-5-5"})]}):d(ve,{children:[n("path",{d:"M11 17l-5-5 5-5"}),n("path",{d:"M18 17l-5-5 5-5"})]})})})}),n("div",{className:"absolute inset-0 flex items-center justify-center gap-1 pointer-events-none",children:d("div",{className:"flex items-center gap-1 pointer-events-auto",children:[Pr.map(te=>{const me=Ys(te),Se=me==="desktop"?"Desktop":me==="laptop"?"Laptop":me==="tablet"?"Tablet":"Mobile";return d("button",{onClick:()=>{dt&&Sr(!1),xh(te)},className:`p-1.5 rounded transition-colors cursor-pointer ${!dt&&Le.name===te.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${te.name} (${te.width}×${te.height})`,children:[Se==="Desktop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),Se==="Laptop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),Se==="Tablet"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),Se==="Mobile"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},te.name)}),d("div",{className:"relative",children:[d("button",{onClick:()=>{dt||Nr(te=>!te)},className:`flex items-center gap-1.5 px-2 py-1 rounded transition-colors ${dt?"":"cursor-pointer"} ${dt||ts||!Pr.some(te=>te.name===Le.name)?"text-white bg-[#555]":"text-gray-400 hover:text-gray-200 hover:bg-[#444]"}`,title:"Custom dimensions",children:[n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),n("span",{className:"text-xs font-mono",children:dt&&Cn?`${Math.round(Cn.width)} × ${Math.round(Cn.height)}`:`${Le.width} × ${Le.height??900}`})]}),ts&&n(ay,{currentWidth:Le.width,currentHeight:Le.height??900,devicePresets:Pr,customSizes:Wo,onApply:vh,onSave:bh,onRemove:hh,onClose:()=>Nr(!1)})]}),n("button",{onClick:()=>{Sr(te=>!te)},className:`p-1.5 rounded transition-colors cursor-pointer ${dt?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:dt?"Exit fullscreen":"Fill page with preview",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:dt?d(ve,{children:[n("polyline",{points:"4 14 10 14 10 20"}),n("polyline",{points:"20 10 14 10 14 4"}),n("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):d(ve,{children:[n("polyline",{points:"15 3 21 3 21 9"}),n("polyline",{points:"9 21 3 21 3 15"}),n("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})}),n("button",{onClick:()=>{const te=Go||qn;te&&window.open(te,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})})]}),lh&&n(pE,{onSaveToCurrent:()=>void ml("overwrite"),onSaveAsNew:()=>void ml("new"),onDismiss:()=>Vn(!1),isSaving:ch,scenarioName:(kl=a.find(te=>{var me;return te.id===(be||((me=Ss(a))==null?void 0:me.id))}))==null?void 0:kl.name}),n("div",{ref:I,className:`flex-1 flex ${Un||ht?"overflow-y-auto overflow-x-hidden":"overflow-hidden"} ${dt?"":"items-center justify-center p-8"}`,style:dt?{backgroundColor:"#fff"}:Un?{backgroundColor:"#f5f0e8",backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px), repeating-linear-gradient(90deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px)"}:ht?{backgroundColor:"#1e1e1e"}:{backgroundImage:`
|
|
761
|
+
linear-gradient(45deg, #333 25%, transparent 25%),
|
|
762
|
+
linear-gradient(-45deg, #333 25%, transparent 25%),
|
|
763
|
+
linear-gradient(45deg, transparent 75%, #333 75%),
|
|
764
|
+
linear-gradient(-45deg, transparent 75%, #333 75%)
|
|
765
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:Un?n(lE,{preview:Un,viewportWidth:Le.width,viewportHeight:Le.height??900,scale:an,onDismiss:()=>Ft(null),onLoadCommit:ft}):ht?n(dE,{preview:ht,viewportWidth:Le.width,viewportHeight:Le.height??900,scale:an,onDismiss:()=>mt(null)}):qn?dt?d("div",{className:"relative w-full h-full bg-white",children:[!xr&&!hs&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Gt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),hs&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:F,src:Go||qn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Sl,style:{opacity:xr?1:0}},Jn)]}):n("div",{style:{width:`${(jr?Le.width+$s.width:Le.width)*an}px`,height:`${(jr?(Le.height??900)+$s.height:Le.height??900)*an}px`},children:n("div",{className:"origin-top-left",style:{transform:an<1?`scale(${an})`:void 0},children:n(Hk,{width:Le.width,height:Le.height??900,enabled:jr,children:d("div",{className:"relative bg-white",style:{width:`${Le.width}px`,height:`${Le.height??900}px`},children:[!xr&&!hs&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Gt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),hs&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:F,src:Go||qn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Sl,style:{opacity:xr?1:0}},Jn)]})})})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${Le.width*an}px`,height:`${(Le.height??900)*an}px`},children:Oe?d("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:Oe}),n("button",{onClick:bt,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):xe||vr?d(ve,{children:[n("div",{className:"mb-4",children:n(Gt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:vr?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:vr?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]})]})]})}),n(Sd,{})]})}),jE=Object.freeze(Object.defineProperty({__proto__:null,default:_E,loader:kE,meta:SE,shouldRevalidate:NE},Symbol.toStringTag,{value:"Module"})),PE=nt(function(){return null}),er=Object.freeze(Object.defineProperty({__proto__:null,default:PE},Symbol.toStringTag,{value:"Module"})),D_={entry:{module:"/assets/entry.client-j1Vi0bco.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.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,hasDefaultExport:!0,hasErrorBoundary:!0,module:"/assets/root-BRyJWJBA.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/useReportContext-jkCytuYz.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.js","/assets/book-open-BFSIqZgO.js","/assets/useToast-BgqkixU9.js","/assets/useLastLogLine-C8QvIe05.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/chevron-down-B9fDzFVh.js","/assets/circle-check-DLPObLUx.js","/assets/CopyButton-DTBZZfSk.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DziaVQX1.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-C8AyYgYT.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.js","/assets/editorPreview-C6fEYHrh.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-scenario-data-l0sNRNKZ.js",imports:[],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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-D_O_ajfZ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-coverage-l0sNRNKZ.js",imports:[],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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-BTcpgIpC.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-recapture-stale-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-rename-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-seed-state-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-prompt-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],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,hasDefaultExport:!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.editor-hosting-verify":{id:"routes/api.editor-hosting-verify",parentId:"root",path:"api/editor-hosting-verify",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-hosting-verify-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-github-verify":{id:"routes/api.editor-github-verify",parentId:"root",path:"api/editor-github-verify",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-github-verify-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-verify-routes-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,hasDefaultExport:!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.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-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,hasDefaultExport:!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,hasDefaultExport:!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.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-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,hasDefaultExport:!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,hasDefaultExport:!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.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-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,hasDefaultExport:!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.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-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,hasDefaultExport:!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.editor-handoff":{id:"routes/api.editor-handoff",parentId:"root",path:"api/editor-handoff",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-handoff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-roadmap-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-session-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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-B8NCeOrm.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/search-BooqacKS.js","/assets/chevron-down-B9fDzFVh.js","/assets/book-open-BFSIqZgO.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-schema-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DqM9hbNE.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/LogViewer-C-9zQdXg.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/loader-circle-D-q28GLF.js","/assets/pause-BP6fitdh.js","/assets/createLucideIcon-BwyFiRot.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,hasDefaultExport:!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.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha._-pc-vc6wO.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/LoadingDots-By5zI316.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/createLucideIcon-BwyFiRot.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/CopyButton-DTBZZfSk.js","/assets/LogViewer-C-9zQdXg.js","/assets/MiniClaudeChat-Bs2_Oua4.js","/assets/useReportContext-jkCytuYz.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-ByaELMbv.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.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,hasDefaultExport:!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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/simulations-ovy6FjRY.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/dev.empty-iRhRIFlp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/LogViewer-C-9zQdXg.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-ByaELMbv.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/settings-BM0nbryO.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/CopyButton-DTBZZfSk.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.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,hasDefaultExport:!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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/_index-DnOgyseQ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useToast-BgqkixU9.js","/assets/useReportContext-jkCytuYz.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/loader-circle-D-q28GLF.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/memory-CEWIUC4t.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/copy-DXEmO0TD.js","/assets/CopyButton-DTBZZfSk.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/pause-BP6fitdh.js","/assets/book-open-BFSIqZgO.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/files-kuny2Q_s.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/labs-c3yLxSEp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/git-DgCZPMie.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/LogViewer-C-9zQdXg.js","/assets/index-SqjQKTdH.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor.entity.(_sha)-D4cIaQC3.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/editorPreview-C6fEYHrh.js","/assets/CopyButton-DTBZZfSk.js","/assets/MiniClaudeChat-Bs2_Oua4.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/Spinner-CIil5-gb.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useLastLogLine-C8QvIe05.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-985e63d6.js",version:"985e63d6",sri:void 0},I_="build/client",O_="/",L_={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},z_=!0,B_=!1,Y_=[],U_={mode:"lazy",manifestPath:"/__manifest"},W_="/",J_={module:Jm},H_={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:sy},"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:dy},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:Uy},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,module:Cx},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:Ex},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,module:jx},"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:qx},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:bb},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,module:Sb},"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:Ab},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:$b},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:Rb},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:Ib},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,module:Qb},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,module:Xb},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,module:tv},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,module:rv},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:ov},"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:mw},"routes/api.editor-hosting-verify":{id:"routes/api.editor-hosting-verify",parentId:"root",path:"api/editor-hosting-verify",index:void 0,caseSensitive:void 0,module:bw},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:Mw},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:Fw},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:Dw},"routes/api.editor-github-verify":{id:"routes/api.editor-github-verify",parentId:"root",path:"api/editor-github-verify",index:void 0,caseSensitive:void 0,module:Bw},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:Uw},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:Jw},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,module:Vw},"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:qw},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,module:Xw},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:cN},"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:gN},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:xN},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:PN},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:$N},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:VN},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:QN},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:e1},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:n1},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:s1},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:i1},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:d1},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:p1},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:f1},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:E1},"routes/api.editor-handoff":{id:"routes/api.editor-handoff",parentId:"root",path:"api/editor-handoff",index:void 0,caseSensitive:void 0,module:T1},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:$1},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:B1},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,module:tS},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,module:rS},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:lS},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:pS},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:gS},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:xS},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:FS},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:DS},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,module:zS},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:YS},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:WS},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:qS},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:ZS},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:lC},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:uC},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:hC},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:yC},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:bC},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:CC},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:KC},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:QC},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:s2},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:a2},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:l2},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:N2},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:k2},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:j2},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:R2},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:I2},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:H2},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:yk},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Sk},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Mk},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Uk},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:jE},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,module:er},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,module:er},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,module:er},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,module:er},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,module:er},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,module:er}},V_=!1;export{Of as $,$g as A,Ag as B,Dg as C,_g as D,$e as E,Qf as F,Zf as G,Ln as H,C_ as I,gf as J,xf as K,bf as L,vf as M,Ld as N,Nf as O,Sf as P,zd as Q,kf as R,Ef as S,Bf as T,Bd as U,Af as V,Mf as W,$f as X,Ff as Y,Df as Z,If as _,cf as a,Lf as a0,mf as a1,ff as a2,zf as a3,Gs as a4,Uf as a5,Wf as a6,Jf as a7,Hf as a8,Kf as a9,B_ as aA,Y_ as aB,U_ as aC,W_ as aD,J_ as aE,H_ as aF,V_ as aG,D_ as aH,Vf as aa,P_ as ab,pi as ac,A_ as ad,M_ as ae,T_ as af,j_ as ag,R_ as ah,De as ai,Kg as aj,Hg as ak,o0 as al,Qr as am,k_ as an,Vd as ao,Bg as ap,Yg as aq,I1 as ar,F_ as as,bn as at,E_ as au,__ as av,I_ as aw,O_ as ax,L_ as ay,z_ as az,Rn as b,Fn as c,Zt as d,qr as e,ii as f,po as g,Od as h,af as i,ug as j,pg as k,gn as l,Xt as m,ci as n,vg as o,Qs as p,tt as q,Wd as r,Jd as s,di as t,pn as u,Hd as v,pr as w,or as x,cg as y,zl as z};
|