@codeyam/codeyam-cli 0.1.0-staging.a890816 → 0.1.0-staging.ad44cd3
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/log.txt +3 -3
- package/analyzer-template/package.json +10 -10
- package/analyzer-template/packages/ai/package.json +2 -2
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +0 -33
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +13 -7
- package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
- package/analyzer-template/packages/aws/package.json +2 -2
- package/analyzer-template/packages/database/package.json +3 -3
- package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +102 -0
- package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
- package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +0 -65
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +9 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +104 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +0 -25
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.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/package.json +1 -1
- package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
- package/analyzer-template/packages/ui-components/package.json +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/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 +9 -0
- package/codeyam-cli/src/cli.js.map +1 -1
- 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.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 +101 -47
- package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
- package/codeyam-cli/src/commands/default.js +3 -46
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/editor.js +3916 -419
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/commands/editorIsolateArgs.js +25 -0
- package/codeyam-cli/src/commands/editorIsolateArgs.js.map +1 -0
- package/codeyam-cli/src/commands/init.js +74 -35
- package/codeyam-cli/src/commands/init.js.map +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/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__/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 +137 -0
- package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +1879 -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__/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 +261 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.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 +353 -0
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +153 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.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 +221 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +1483 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +280 -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 +1857 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
- 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__/journalCaptureStabilization.test.js +107 -0
- package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.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__/project.test.js +65 -0
- package/codeyam-cli/src/utils/__tests__/project.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 +227 -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 +493 -0
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +26 -5
- 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__/webappDetection.test.js +142 -0
- package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
- package/codeyam-cli/src/utils/analysisRunner.js +3 -1
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/analyzer.js +9 -0
- 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 +94 -18
- 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/database.js +37 -2
- package/codeyam-cli/src/utils/database.js.map +1 -1
- 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 +79 -0
- package/codeyam-cli/src/utils/editorApi.js.map +1 -0
- package/codeyam-cli/src/utils/editorAudit.js +355 -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 +129 -0
- package/codeyam-cli/src/utils/editorEntityHelpers.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 +137 -0
- package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
- package/codeyam-cli/src/utils/editorScenarioSwitch.js +112 -0
- package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
- package/codeyam-cli/src/utils/editorScenarios.js +548 -0
- package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js +422 -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/entityChangeStatus.js +366 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js +196 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
- package/codeyam-cli/src/utils/fileWatcher.js +38 -0
- package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
- package/codeyam-cli/src/utils/git.js +51 -0
- package/codeyam-cli/src/utils/git.js.map +1 -1
- package/codeyam-cli/src/utils/install-skills.js +37 -17
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
- package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
- package/codeyam-cli/src/utils/progress.js +2 -2
- 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/routePatternMatching.js +129 -0
- package/codeyam-cli/src/utils/routePatternMatching.js.map +1 -0
- package/codeyam-cli/src/utils/scenarioCoverage.js +74 -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 +249 -0
- package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
- package/codeyam-cli/src/utils/serverState.js +30 -0
- package/codeyam-cli/src/utils/serverState.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +47 -16
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/simulationGateMiddleware.js +8 -1
- package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -1
- 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 +2 -2
- package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +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/testRunner.js +1 -1
- package/codeyam-cli/src/utils/testRunner.js.map +1 -1
- package/codeyam-cli/src/utils/webappDetection.js +21 -0
- package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
- 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 +40 -0
- package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +628 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +146 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js +65 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
- 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/types/editor.js +8 -0
- package/codeyam-cli/src/webserver/app/types/editor.js.map +1 -0
- package/codeyam-cli/src/webserver/backgroundServer.js +18 -4
- package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CzTDWkF2.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BFbq6iFk.js} +5 -5
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-CQgyEGV-.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-B6OMi58N.js} +9 -9
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-DuYodzo1.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-CXo9EeCl.js +25 -0
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DYCNb2It.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-BU_OAEMP.js → LoadingDots-By5zI316.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-ceAyBX-H.js → LogViewer-CZgY3sxX.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-CnYYwRDw.js} +4 -4
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CDoF7ZpU.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-B76aig_2.js → ScenarioViewer-DrnfvaLL.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/Spinner-Df3UCi8k.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-DRKR9T0U.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-ClR-g3tY.js} +4 -4
- package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-DTH6ydEA.js} +8 -8
- 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-Duc5hnl7.js → addon-web-links-74hnHF59.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
- package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-B8CYhCO9.js} +7 -7
- 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-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-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-rename-scenario-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-prompt-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/{book-open-D_nMCFmP.js → book-open-CLaoh4ac.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-BZ2DZxbW.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{chunk-JZWAC4HX-C4pqxYJB.js → chunk-JZWAC4HX-BBXArFPl.js} +13 -21
- package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-CT4unAk-.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-zK0B6Nu-.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-DJB0YQJL.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CkXFP_i-.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor._tab-DPw7NZHc.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-CjC3_6JI.js +58 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-DBa7T2FK.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CrjR3zZW.js → entity._sha._-BqAN7hyG.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-BOi8kpwd.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-Dg1NhIms.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CJX6kkkV.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-BMvVHNXU.js → entity._sha_.edit._scenarioId-BhVjZhKg.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{entry.client-DTvKq3TY.js → entry.client-_gzKltPN.js} +6 -6
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-Daa96Fr1.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-CV_17tZS.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-D-YXmMbR.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-DRvOjyO3.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-Blo6EK8G.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/{index-10oVnAAH.js → index-BsX0F-9C.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{index-BcvgDzbZ.js → index-CCrgCshv.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/jsx-runtime-D_zvdyIk.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/labs-Byazq8Pv.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DVQ0oHR7.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/manifest-75b1b319.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/memory-b-VmA2Vj.js +101 -0
- package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-DGcndCAa.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/root-F-k2uYj5.js +67 -0
- package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-C0Uw0bcK.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/settings-OoNgHIfW.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-Bcemfu8a.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-BgMmG7R9.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-Cs87hJYK.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BR3Rs7JY.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-C14nCb1q.js → useLastLogLine-BxxP_XF9.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BermyNU5.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/useToast-a_QN_W9_.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-lv2ooewK.js +13 -0
- package/codeyam-cli/src/webserver/build/server/assets/index-Im3Smyei.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/init-BjuAFKGM.js +10 -0
- package/codeyam-cli/src/webserver/build/server/assets/progress-CHTtrxFG.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-CNjF0B9B.js +551 -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/editorProxy.js +755 -51
- package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
- package/codeyam-cli/src/webserver/idleDetector.js +73 -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 +94 -4
- package/codeyam-cli/src/webserver/server.js +176 -12
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +218 -140
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
- 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 +84 -5
- package/codeyam-cli/templates/editor-step-hook.py +198 -22
- package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -0
- package/codeyam-cli/templates/expo-react-native/README.md +41 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/_layout.tsx +33 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/index.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/settings.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app.json +18 -0
- package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
- package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
- package/codeyam-cli/templates/expo-react-native/global.css +3 -0
- package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -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 +38 -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/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/codeyam-isolate/layout.tsx +12 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +9 -4
- package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +21 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +5 -1
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
- package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +127 -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-sqlite/PRISMA_SETUP.md → nextjs-prisma-supabase/SUPABASE_SETUP.md} +37 -17
- 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/seed-adapters/supabase.ts +282 -0
- package/codeyam-cli/templates/{codeyam-dev-mode.md → skills/codeyam-dev-mode/SKILL.md} +3 -3
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +211 -0
- package/codeyam-cli/templates/{codeyam-memory.md → skills/codeyam-memory/SKILL.md} +215 -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/package.json +16 -10
- package/packages/ai/src/lib/generateExecutionFlows.js +0 -11
- package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
- package/packages/analyze/src/lib/ProjectAnalyzer.js +10 -4
- package/packages/analyze/src/lib/ProjectAnalyzer.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/files/scenarios/generateExecutionFlows.js +0 -40
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +104 -0
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
- package/packages/database/src/lib/loadEntities.js +0 -6
- package/packages/database/src/lib/loadEntities.js.map +1 -1
- package/packages/database/src/lib/updateCommitMetadata.js +0 -25
- package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
- package/packages/types/src/enums/ProjectFramework.js +2 -0
- package/packages/types/src/enums/ProjectFramework.js.map +1 -1
- package/scripts/npm-post-install.cjs +34 -0
- package/codeyam-cli/src/webserver/build/client/assets/CopyButton-DmJveP3T.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-g3saevPb.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-Bu6c6aDe.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-DYFW3lDD.js +0 -25
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DLeucoVX.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BED4B6sP.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/Spinner-Bb5uFQ5V.js +0 -34
- package/codeyam-cli/src/webserver/build/client/assets/Terminal-CcG8YTLx.js +0 -41
- package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-C8OKAR5x.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CMT1jU2q.js +0 -21
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/editor-W_IGJ2Kd.js +0 -7
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-D6SEzMCu.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-p9hhkjJM.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-cPo8LiG3.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/files-DO4CZ16O.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-CFCTYk9I.js +0 -15
- package/codeyam-cli/src/webserver/build/client/assets/globals-BZB_H1w2.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/labs-Zk7ryIM1.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-8daa4147.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-FweZHj5U.js +0 -93
- package/codeyam-cli/src/webserver/build/client/assets/root-DiRdBreB.js +0 -67
- package/codeyam-cli/src/webserver/build/client/assets/settings-DfuTtcJP.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/simulations-B3aOzpCZ.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-ByhSyh0W.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-O-jkvSPx.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useToast-9FIWuYfK.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/xterm-DMSzMhqy.js +0 -9
- package/codeyam-cli/src/webserver/build/server/assets/index-BzAbACSx.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-OdUocH6P.js +0 -362
- package/codeyam-cli/templates/codeyam-editor.md +0 -68
- package/scripts/finalize-analyzer.cjs +0 -13
- /package/codeyam-cli/templates/{codeyam-diagnose.md → commands/codeyam-diagnose.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-debug.md → skills/codeyam-debug/SKILL.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-new-rule.md → skills/codeyam-new-rule/SKILL.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-setup.md → skills/codeyam-setup/SKILL.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-sim.md → skills/codeyam-sim/SKILL.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-test.md → skills/codeyam-test/SKILL.md} +0 -0
- /package/codeyam-cli/templates/{codeyam-verify.md → skills/codeyam-verify/SKILL.md} +0 -0
|
@@ -1,362 +0,0 @@
|
|
|
1
|
-
var gl=Object.defineProperty;var Pa=e=>{throw TypeError(e)};var yl=(e,t,r)=>t in e?gl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ln=(e,t,r)=>yl(e,typeof t!="symbol"?t+"":t,r),xl=(e,t,r)=>t.has(e)||Pa("Cannot "+r);var _a=(e,t,r)=>(xl(e,t,"read from private field"),r?r.call(e):t.get(e)),ja=(e,t,r)=>t.has(e)?Pa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as ue}from"react/jsx-runtime";import{PassThrough as bl}from"node:stream";import{createReadableStreamFromReadable as vl}from"@react-router/node";import{ServerRouter as wl,useFetcher as Le,useLocation as gr,useNavigate as ft,Link as de,UNSAFE_withComponentProps as Ue,Meta as Cl,Links as Nl,ScrollRestoration as Sl,Scripts as kl,useLoaderData as Je,useRevalidator as lt,Outlet as El,data as V,useSearchParams as sn,useRouteLoaderData as Al,useParams as Po,useActionData as Pl,redirect as Ma}from"react-router";import{isbot as _l}from"isbot";import{renderToPipeableStream as jl}from"react-dom/server";import{useState as _,useEffect as X,useCallback as ie,createContext as Ts,useContext as yr,useRef as be,useMemo as ae,forwardRef as Ml,useImperativeHandle as Tl}from"react";import{Settings as Ta,CheckCircle2 as $s,Bug as _o,AlertTriangle as er,Check as ct,Copy as pt,Loader2 as at,PencilRuler as $l,HomeIcon as Il,GitCommitIcon as $a,File as Rl,RefreshCw as Dl,BookOpen as tr,FlaskConical as Ll,SettingsIcon as Ol,PanelsTopLeftIcon as Fl,ComponentIcon as zl,FileText as Ia,Code as Ra,Box as Yl,List as Bl,BarChart3 as Ul,Tag as Wl,Image as Sn,Code2 as jo,Activity as Jr,ChevronDown as nt,CircleEqual as Hl,ArrowLeft as Jl,Terminal as nr,Search as Pn,ChevronLeft as Vl,ChevronRight as Mt,Save as ql,MessageSquare as Gl,Pause as Mo,ListTodo as Kl,PauseCircle as Ql,FileCode as rr,GripVertical as Zl,Ban as Xl,CheckCircle as ec,FolderOpen as tc,CodeXml as nc,Zap as rc,Pencil as sc,Trash2 as ac,X as _n,Folder as To,Info as gs,Plus as Is,Eye as oc,FolderTree as ic,ChevronsUpDown as $o,ChevronsDownUp as Io}from"lucide-react";import"fetch-retry";import lc from"better-sqlite3";import{Pool as cc}from"pg";import*as Q from"fs";import Ae,{existsSync as kt,readdirSync as dc,rmSync as Vr}from"fs";import*as B from"path";import te,{join as Da}from"path";import{OperationNodeTransformer as uc,Kysely as Ro,ParseJSONResultsPlugin as hc,SqliteDialect as mc,PostgresDialect as pc,sql as tt}from"kysely";import*as fc from"kysely/helpers/sqlite";import*as gc from"kysely/helpers/postgres";import Ye from"typescript";import*as Ce from"fs/promises";import ye,{writeFile as bn,readFile as ys,mkdir as yc}from"fs/promises";import*as Do from"os";import xs from"os";import xc from"prompts";import sr from"chalk";import*as bc from"crypto";import xr,{randomUUID as Rs,createHmac as vc}from"crypto";import{execSync as je,spawn as gt,exec as Ds}from"child_process";import{fileURLToPath as br}from"url";import{promisify as Ls}from"util";import wc from"dotenv";import Cc,{EventEmitter as vr}from"events";import{v4 as Nc}from"uuid";import Lo from"http";import Sc from"net";import{WebSocket as kc}from"ws";import"node-pty";import Ec from"openai";import Ac from"p-queue";import La from"p-retry";import{DynamoDBClient as wr,PutItemCommand as Pc}from"@aws-sdk/client-dynamodb";import{LRUCache as Os}from"lru-cache";import"pluralize";import"piscina";import _c from"json5";import{marshall as jc}from"@aws-sdk/util-dynamodb";import Mc from"v8";import{Prism as Tc}from"react-syntax-highlighter";import{vscDarkPlus as $c}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ic}from"node:crypto";import{minimatch as bs}from"minimatch";import Rc from"react-markdown";import Dc from"remark-gfm";import Lc from"react-diff-viewer-continued";const Oo=5e3;function Oc(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),h=d&&_l(d)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),Oo+1e3);const{pipe:m,abort:p}=jl(n(wl,{context:s,url:e.url}),{[h](){c=!0;const f=new bl({final(g){clearTimeout(u),u=void 0,g()}}),y=vl(f);r.set("Content-Type","text/html"),m(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const Fc=Object.freeze(Object.defineProperty({__proto__:null,default:Oc,streamTimeout:Oo},Symbol.toStringTag,{value:"Module"}));function zc({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=_(!1);X(()=>{i(!0)},[]);const c=ie(()=>{r==null||r(e)},[r,e]);return l("button",{className:`
|
|
2
|
-
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
-
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
-
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
-
`,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const Cr="/assets/cy-logo-cli-CCKUIm0S.svg";function Yc(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 Bc({content:e,className:t=""}){const[r,s]=_(!1),a=ie(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(ue,{children:[n(ct,{size:14}),"Copied"]}):l(ue,{children:[n(pt,{size:14}),"Copy"]})})}function Fo({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=_(""),[c,d]=_(s),[h,u]=_(!1),[m,p]=_(!1),[f,y]=_(null),[g,x]=_(null),v=Le(),b=v.state!=="idle",w=!!(r.scenarioId||r.analysisId),N=r.analysisId||r.scenarioId||"",C=()=>{const k=`/codeyam-diagnose ${N}`;return o.trim()?`${k} ${o.trim()}`:k};if(v.data&&!m&&!g){const k=v.data;k.success&&k.reportId?(p(!0),y(k.reportId)):k.error&&x(k.error)}const S=async()=>{x(null);const k=new FormData;if(k.append("issueType","other"),k.append("description",o),k.append("email",c),k.append("source",r.source),k.append("entitySha",r.entitySha||""),k.append("scenarioId",r.scenarioId||""),k.append("analysisId",r.analysisId||""),k.append("currentUrl",r.currentUrl),k.append("entityName",r.entityName||""),k.append("entityType",r.entityType||""),k.append("scenarioName",r.scenarioName||""),k.append("errorMessage",r.errorMessage||""),a)try{const R=await(await fetch(a)).blob();k.append("screenshot",R,"screenshot.jpg")}catch(j){console.error("Failed to convert screenshot:",j)}v.submit(k,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},A=()=>{i(""),u(!1),p(!1),y(null),x(null),t()},E=k=>{k.key==="Escape"&&A()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:E,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(Ta,{size:24,style:{strokeWidth:1.5}})}):m?n($s,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(_o,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:A,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:A,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:Yc(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:k=>i(k.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),w&&l(ue,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:C()}),n(Bc,{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"})]})]}),l("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:w?"opacity-75":"",children:[w&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:k=>d(k.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(er,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.formData?"Uploading report...":"Creating archive..."})}),g&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(er,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:A,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void S(),disabled:b,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:b?l(ue,{children:[n("div",{className:"animate-spin",children:n(Ta,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Oa={source:"navbar"},Fs=Ts(void 0);function Uc({children:e}){const[t,r]=_(Oa),s=ie(o=>{r(o)},[]),a=ie(()=>{r(Oa)},[]);return n(Fs.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function dt(e){const t=yr(Fs),r=be(t);X(()=>{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 Wc(){const e=yr(Fs),t=gr();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 Hc({labs:e,isAdmin:t,editorMode:r}){var S;const s=gr(),a=ft(),[o,i]=_(),[c,d]=_(!1),[h,u]=_(!1),[m,p]=_(null),f=Le();X(()=>{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,v=[{id:"editor",icon:n($l,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(Il,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:l("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},{id:"git",icon:n($a,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(Rl,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(Dl,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(tr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Ll,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Ol,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n($a,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Fl,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(zl,{style:g}),link:"/components",name:"Components",hidden:!0}],b=ie(A=>{const E=v.find(k=>k.id===A);E!=null&&E.link&&a(E.link),i(k=>k===A?void 0:A)},[v,a]);X(()=>{const A={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[E,k]of Object.entries(A))if(k.some(j=>j==="/"?s.pathname==="/":s.pathname.includes(j))){i(E);return}i(void 0)},[s]);const w=async()=>{u(!0);try{const{default:A}=await import("html2canvas-pro"),k=(await A(document.body)).toDataURL("image/jpeg",.8);p(k),d(!0)}catch(A){console.error("Screenshot capture failed:",A),d(!0)}finally{u(!1)}},N=()=>{d(!1),p(null)},C=Wc();return l(ue,{children:[l("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(de,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Cr,alt:"CodeYam",className:"h-6"})})}),v.filter(A=>!A.hidden).map(A=>n(zc,{id:A.id,selected:A.id===o,onClick:b,icon:A.icon,name:A.name},`sidebar-button-${A.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void w(),disabled:h,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:h?n(at,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(_o,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:h?"Capturing...":`Report
|
|
6
|
-
Bug`})]})})]}),c&&n(Fo,{isOpen:!0,onClose:N,context:C,defaultEmail:y,screenshotDataUrl:m??void 0})]})}const zo=Ts(void 0);function Jc({children:e}){const[t,r]=_([]),s=ie((o,i="info",c=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,h])},[]),a=ie(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(zo.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function zs(){const e=yr(zo);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Vc({toast:e,onClose:t}){X(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return l("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function qc({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
-
@keyframes slideIn {
|
|
8
|
-
from {
|
|
9
|
-
transform: translateX(400px);
|
|
10
|
-
opacity: 0;
|
|
11
|
-
}
|
|
12
|
-
to {
|
|
13
|
-
transform: translateX(0);
|
|
14
|
-
opacity: 1;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
`}),e.map(r=>n(Vc,{toast:r,onClose:t},r.id))]})}function yt(e,t){const[r,s]=_(""),[a,o]=_(!1),[i,c]=_(null),[d,h]=_(!1);X(()=>{t&&(h(!1),o(!1),c(null))},[t]),X(()=>{if(!e||!t){t||s("");return}const m=async()=>{if(!d)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
-
`).filter(b=>b.length>0);if(g.length<3){o(!1),h(!1),c(null),s("");return}const x=g.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];s(b.replace(/.*CodeYam Log Level 1: /,""))}const v=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),h(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},500);return()=>clearInterval(p)},[e,t,d]);const u=ie(()=>{s(""),o(!1),c(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function At({projectSlug:e,onClose:t}){const[r,s]=_("Loading logs..."),[a,o]=_(!0),[i,c]=_(!0),[d,h]=_("all"),u=be(null);return X(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="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])<=d});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
-
`))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${p.status} - ${await p.text()}`)}catch(p){s(`Error fetching logs: ${p.message}`)}};if(m().catch(()=>{}),a){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,a,i,d]),X(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:m=>h(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>c(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function Qe({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,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(jo,{size:a,color:s.iconColor});case"visual":return n(Sn,{size:a,color:s.iconColor});case"type":return n(Wl,{size:a,color:s.iconColor});case"data":return n(Ul,{size:a,color:s.iconColor});case"index":return n(Bl,{size:a,color:s.iconColor});case"functionCall":return n(Ra,{size:a,color:s.iconColor});case"class":return n(Yl,{size:a,color:s.iconColor});case"method":return n(Ra,{size:a,color:s.iconColor});case"other":return n(Ia,{size:a,color:s.iconColor});default:return n(Ia,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Yo({filePath:e,maxLength:t=60,className:r,style:s}){const o=((c,d)=>{if(c.length<=d)return c;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,m),y=c.slice(-p),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>m*.5?f.slice(0,g+1):f,b=x!==-1&&x<p*.5?y.slice(x):y;return`${v}${h}${b}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function qr({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(Qe,{type:e.entityType||"other"}),l(de,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(Yo,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Gr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Gc({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var K,H,U;const[d,h]=_(!1),[u,m]=_(!1),[p,f]=_(null),[y,g]=_(new Set),[x,v]=_(new Set),[b,w]=_(!1),N=!!i||o.length>0,C=!!i,S=(i==null?void 0:i.entities)||r,A=!!(e!=null&&e.analysisCompletedAt),E=(e==null?void 0:e.readyToBeCaptured)??0,k=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||A&&(E===0||k>=E);const j=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,R=N,{lastLine:M}=yt(t,R),I=C||o.length>0,$=new Set(((K=i==null?void 0:i.entities)==null?void 0:K.map(F=>F.sha))||[]),T=c.filter(F=>!(F.currentEntityShas||[]).some(P=>$.has(P))),q=(()=>{const L=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&j){const P=e.analysisCompletedAt||e.createdAt;if(new Date(P).getTime()>L)return!0}if(T.length>0){const P=T[0],O=P.analysisCompletedAt||P.archivedAt||P.createdAt;if(O&&new Date(O).getTime()>L)return!0}return!1})();return X(()=>{const F=(i==null?void 0:i.id)||null;N&&!u&&F!==p&&m(!0),!N&&p!==null&&f(null)},[N,i==null?void 0:i.id,u,p]),l(ue,{children:[l("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&l("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[I?n(at,{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(Jr,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:I?"Analyzing...":"Activity: No Activity Yet"}),I&&n("button",{onClick:F=>{F.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[I?n(at,{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(Jr,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:I?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(nt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[I&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Jr,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:S.length>0?l("div",{className:"space-y-1.5",children:[(b?S:S.slice(0,3)).map(F=>n(qr,{entity:F,nameSize:"11px",pathSize:"10px",pathMaxLength:150},F.sha)),S.length>3&&n("button",{onClick:()=>w(F=>!F),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gr,"aria-label":b?"Show fewer entities":`Show ${S.length-3} more entities`,children:b?"Show less":`+${S.length-3} more`}),M&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:M})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((F,L)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:F},L)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((H=i.entityShas)==null?void 0:H.length)||0," ",((U=i.entityShas)==null?void 0:U.length)===1?"entity":"entities","..."]}),M&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:M})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Hl,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(F=>{var O,z;const L=y.has(F.id),P=L?F.entities:F.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:F.entities.length>0?l("div",{className:"space-y-1.5",children:[P.map(J=>n(qr,{entity:J,nameSize:"10px",pathSize:"9px",pathMaxLength:120},J.sha)),F.entities.length>3&&n("button",{onClick:()=>{g(J=>{const ee=new Set(J);return ee.has(F.id)?ee.delete(F.id):ee.add(F.id),ee})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gr,"aria-label":L?"Show fewer entities":`Show ${F.entities.length-3} more entities`,children:L?"Show less":`+${F.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[F.type==="analysis"&&n(ue,{children:F.entityNames&&F.entityNames.length>0?l("div",{className:"space-y-0.5",children:[F.entityNames.slice(0,5).map((J,ee)=>n("div",{children:J},ee)),F.entityNames.length>5&&l("div",{className:"italic",children:["+",F.entityNames.length-5," more"]})]}):`Analyzing ${((O=F.entityShas)==null?void 0:O.length)||0} ${((z=F.entityShas)==null?void 0:z.length)===1?"entity":"entities"}`}),F.type==="recapture"&&"Recapturing scenario",F.type==="debug-setup"&&"Setting up debug environment"]})},F.id)})})]}),q&&T.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n($s,{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:T.slice(0,3).map((F,L)=>{const P=F.entities||[],O=F.analysisCompletedAt||F.archivedAt||F.createdAt||"",z=(()=>{if(!O)return"";const D=Date.now()-new Date(O).getTime(),W=Math.floor(D/6e4),G=Math.floor(D/36e5);return G>0?`${G}h ago`:W>0?`${W}m ago`:"just now"})(),J=x.has(L),Y=(J?P:P.slice(0,3)).map(D=>{var W,G,Z;return{...D,scenarioCount:((Z=(G=(W=D.analyses)==null?void 0:W[0])==null?void 0:G.scenarios)==null?void 0:Z.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:P.length>0&&l("div",{className:"space-y-1.5",children:[Y.map((D,W)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(qr,{entity:D,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:D.scenarioCount})}),W===0&&z&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:z})]},D.sha)),P.length>3&&n("button",{onClick:()=>{v(D=>{const W=new Set(D);return W.has(L)?W.delete(L):W.add(L),W})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Gr,"aria-label":J?"Show fewer entities":`Show ${P.length-3} more entities`,children:J?"Show less":`+${P.length-3} more`})]})},L)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(de,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(At,{projectSlug:t,onClose:()=>h(!1)})]})}function Ze(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function jn(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(g=>g.branch_id),f=c?c.map(xt):void 0,y=d?Ut(d):void 0;return Ze({...m,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function Ys(e){return Ze({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 Bs(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:h,...u}=e;return Ze({...u,branches:t?t.map(tn):void 0,files:r?r.map(Ys):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function Kc(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Ze({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:c})}function Qc(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:c,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Ze({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:c,user:h})}function Bo(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,h=a?xt(a):void 0,u=o?o.map(Kc):void 0,m=i?i.map(Qc):void 0;return Ze({...d,projectId:t,analysisId:r,previousVersionId:s,analysis:h,userScenarios:u,comments:m})}function Zc(e){return Ze({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?xt(e.analysis):void 0,entity:e.entity?jn(e.entity):void 0,branch:e.branch?tn(e.branch):void 0,createdAt:e.created_at})}function xt(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:w,created_at:N,updated_at:C,indirect:S,...A}=e,E=u?jn(u):void 0,k=h?Ys(h):void 0,j=p?Bs(p):void 0,R=m?Ut(m):void 0,M=f?f.map(Bo):void 0,I=y?y.map(Zc):void 0,$=I?I.map(T=>T.branch):void 0;return Ze({...A,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:E,file:k,commit:R,project:j,scenarios:M,analysisBranches:I,branches:$,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:w,createdAt:N,updatedAt:C,indirect:!!S})}function Us(e){return Ze({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Ut(e.commit):void 0,branch:e.branch?tn(e.branch):void 0})}function Xc(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return Ze({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Ut(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:y,...g}=e,x=s?tn(s):void 0,v=i?tn(i):void 0,b=(a==null?void 0:a.length)>0?Xc(a[a.length-1]):void 0,w=(u??[]).map(xt),N=(m??[]).map(jn),C=(p==null?void 0:p.length)>0?p.map(Us):void 0;return h&&(h.username=h.preferredUsername??h.username),Ze({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:c,htmlUrl:d,author:h,analyses:w,entities:N,commitBranches:C,committedAt:f,analyzedAt:y})}function tn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:c,primary:d,...h}=e,u=s?s.map(Ut):void 0,m=a?a.flatMap(p=>xt(p.analysis)):void 0;return Ze({...h,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var pr;class ed{constructor(){ja(this,pr,new td)}transformQuery(t){return _a(this,pr).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}pr=new WeakMap;class td extends uc{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 oe=()=>null,nd={analyzed_at:oe(),configuration:oe(),content_changed_at:oe(),created_at:oe(),description:oe(),github_token:oe(),id:oe(),metadata:oe(),name:oe(),path:oe(),slug:oe(),team_id:oe(),updated_at:oe()},rd=Object.keys(nd),sd={active:oe(),analysis_id:oe(),branch_id:oe(),created_at:oe(),entity_sha:oe(),id:oe()},ad=Object.keys(sd),od={active_at:oe(),content_changed_at:oe(),created_at:oe(),id:oe(),metadata:oe(),name:oe(),primary:oe(),project_id:oe(),ref:oe(),sha:oe(),updated_at:oe()},Uo=Object.keys(od),id={ai_message:oe(),analyzed_at:oe(),author_github_username:oe(),branch_id:oe(),committed_at:oe(),created_at:oe(),files:oe(),html_url:oe(),id:oe(),merged_branch_id:oe(),message:oe(),metadata:oe(),project_id:oe(),sha:oe(),title:oe(),url:oe()},Wo=Object.keys(id),ld=Wo.filter(e=>e!=="files"),cd={commit_id:oe(),created_at:oe(),description:oe(),documentation:oe(),entity_type:oe(),file_id:oe(),file_path:oe(),metadata:oe(),name:oe(),project_id:oe(),quality:oe(),sha:oe(),updated_at:oe()},Ho=Object.keys(cd),dd={active:oe(),branch_id:oe(),entity_sha:oe()},ud=Object.keys(dd),hd={created_at:oe(),deleted:oe(),id:oe(),metadata:oe(),name:oe(),path:oe(),project_id:oe(),updated_at:oe()},md=Object.keys(hd),pd={analysis_id:oe(),approved:oe(),created_at:oe(),description:oe(),id:oe(),metadata:oe(),name:oe(),previous_version_id:oe(),project_id:oe()},ar=Object.keys(pd),fd=!!Wt("ENABLE_QUERY_LOGGING"),gd=!!Wt("ENABLE_QUERY_ERROR_LOGGING");Wt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let On;function Me(){if(!On){const e=Vo();if(e==="sqlite")On=yd();else if(e==="postgresql")On=xd();else throw new Error(`Unknown database type: ${e}`)}return On}function yd(e){if(e||(e=Wt("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=B.dirname(e);if(!Q.existsSync(r))Q.mkdirSync(r,{recursive:!0,mode:493});else try{Q.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new lc(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 a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.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(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new Ro({dialect:new mc({database:s}),plugins:[new hc,new ed],log:Jo})}function xd(){const e=vd();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new cc({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Ro({dialect:new pc({pool:t}),log:Jo})}let Kr=null;function Jt(){return Kr||(Kr=bd(Vo())),Kr}function Jo(e){e.level==="error"?gd&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):fd&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function bd(e){if(e==="sqlite")return fc;if(e==="postgresql")return gc;throw new Error(`Unknown database type: ${e}`)}function Vo(){if(Wt("SQLITE_PATH"))return"sqlite";if(Wt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function vd(){const e=Wt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Wt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var qe=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(qe||{});const Nr="Default Scenario";let wd="<main>";function Cd(){return wd}function Fa(e,...t){_e(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function _e(...e){const t=Cd(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
|
|
21
|
-
${a.stack}`:typeof a=="object"?Nd(a):String(a)}).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 Nd(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(c=>{const d=r(c,a);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(s).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=r(c,a):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function or(e,t){try{let r=function(o){var i,c;if(Ye.isFunctionDeclaration(o)&&fn(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(s),u=Qr(o);a.push({name:d,code:h,sha:Lt(t,d,h),entityType:"function",isDefault:u})}else if(Ye.isClassDeclaration(o)&&fn(o)){const d=((c=o.name)==null?void 0:c.text)||"default",h=o.getText(s),u=Qr(o),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");a.push({name:d,code:h,sha:Lt(t,d,h),entityType:m?"component":"class",isDefault:u})}else if(Ye.isInterfaceDeclaration(o)&&fn(o)){const d=o.name.text,h=o.getText(s);a.push({name:d,code:h,sha:Lt(t,d,h),entityType:"interface",isDefault:!1})}else if(Ye.isTypeAliasDeclaration(o)&&fn(o)){const d=o.name.text,h=o.getText(s);a.push({name:d,code:h,sha:Lt(t,d,h),entityType:"type",isDefault:!1})}else if(Ye.isVariableStatement(o)&&fn(o)){const d=Qr(o);o.declarationList.declarations.forEach(h=>{var u;if(Ye.isIdentifier(h.name)){const m=h.name.text,p=o.getText(s),f=((u=h.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:m,code:p,sha:Lt(t,m,p),entityType:y?"component":"variable",isDefault:d})}})}else if(Ye.isExportAssignment(o)){const d=o.getText(s);a.push({name:"default",code:d,sha:Lt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Ye.isExportDeclaration(o)&&o.exportClause&&Ye.isNamedExports(o.exportClause)){const d=o.getText(s);for(const h of o.exportClause.elements){const u=h.name.text;a.push({name:u,code:d,sha:Lt(t,u,d),entityType:"unknown",isDefault:!1})}}Ye.forEachChild(o,r)};const s=Ye.createSourceFile(t,e,Ye.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function fn(e){if(!Ye.canHaveModifiers(e))return!1;const t=Ye.getModifiers(e);return t?t.some(r=>r.kind===Ye.SyntaxKind.ExportKeyword):!1}function Qr(e){if(!Ye.canHaveModifiers(e))return!1;const t=Ye.getModifiers(e);return t?t.some(r=>r.kind===Ye.SyntaxKind.DefaultKeyword):!1}function Lt(e,t,r){const s=xr.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Sd(e){var h;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],c=[];for(const u of s)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function kd(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=B.normalize(e),s=[...t].sort((a,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=a.path)==null?void 0:c.length)??0)});for(const a of s){const o=B.normalize(a.path??".");if(o==="."||r.startsWith(o+B.sep)||r===o)return a}return t[0]}function Ed(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=kd(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=Sd({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${a}/static/codeyam-sample`}}function Sr(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function Ad(e){const{jsonObjectFrom:t}=Jt();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 Pd({ids:e,analysisId:t}){const r=Me();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 _e("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 _e("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function _d(...e){try{const t=xr.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 Zr(e,t){return t.map(r=>jd(e,r))}function jd(e,t){return tt` ${tt.ref(e)}.${tt.ref(t)}`.as(t)}function Md(e,t,r){return t.map(s=>Td(e,s,r))}function Td(e,t,r){return tt` ${tt.ref(e)}.${tt.ref(t)}`.as(`_cy_${r}:${t}`)}function $d(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const Id=50;function Rd(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 za({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const h=Me(),{jsonObjectFrom:u,jsonArrayFrom:m}=Jt();let p=d?h.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return s&&(p=p.where("entity_name","=",s)),a&&(p=p.where("entity_sha","in",a)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(Zr("scenarios",ar)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(Zr("entities",Ho)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(Zr("scenarios",ar)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Pt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=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:a,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let c=[];if(i){const[d,{arr:h,key:u}]=i,m=Rd(h,Id),p=[];for(let f=0;f<m.length;f++){const y=m[f],x=await za({...e,[u]:y}).execute();x&&p.push(...x)}c=p}else{const h=await za(e).execute();if(!h||h.length===0)return _e("CodeYam: No analyses found",null,e),null;c=h}return c.length===0?null:c.map(xt)}catch(o){return _e("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Dd(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=Jt();let a=e.selectFrom("analysis_branches").select(ad).select(o=>s(o.selectFrom("branches").select(Uo).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function bt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=Me(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):s&&(g=g.where("file_id","=",s)),o&&(g=g.where("entity_name","=",o)),a?g=g.where("commit_id","=",a):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=Jt();g=g.select(N=>{const C=[];return C.push(x(N.selectFrom("entities").select(Ho).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&C.push(x(N.selectFrom("files").select(md).whereRef("files.id","=","analyses.file_id")).as("file")),h&&C.push(x(N.selectFrom("projects").select(rd).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&C.push(v(N.selectFrom("scenarios").select(ar).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&C.push(Dd(N,S=>S.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&C.push(x(N.selectFrom("commits").select(Wo).select(S=>Ad(S).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const b=await g.executeTakeFirst(),w=Date.now()-y;if(!b)return _e("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null;if(w>100&&u){const N=b.commit,C=N!=null&&N.files?JSON.stringify(N.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${w}ms (files: ${Math.round(C/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return xt(b)}catch(g){return _e("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function qo({projectId:e,ids:t,names:r,includeInactive:s}){const a=Me();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(tn)}catch(o){return _e("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Ld({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=Me();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,h=>h.select(Md("branches",Uo,"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 c=await i.execute();return!c||c.length===0?null:c.map(h=>$d(h,"branch")).map(Us)}catch(i){return _e("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function Od(e){if(e.length===0)return new Map;const t=Me();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(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return _e("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Fd(e){if(e.length===0)return new Map;const t=Me(),{jsonObjectFrom:r,jsonArrayFrom:s}=Jt();try{const a=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(ar).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(a){return _e("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function zd(e){if(e.length===0)return new Map;const t=Me();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return _e("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function ir({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=Me(),{jsonObjectFrom:d}=Jt(),h=Date.now();try{let u;if(i){const b=ld.map(w=>`commits.${w}`);u=c.selectFrom("commits").select(b)}else u=c.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const b=tt.join(a.map(w=>tt`${w}`),tt`, `);u=u.where(tt`
|
|
24
|
-
EXISTS (
|
|
25
|
-
SELECT 1
|
|
26
|
-
FROM json_each(${tt.ref("commits.files")}) AS f
|
|
27
|
-
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
-
)
|
|
29
|
-
`)}t&&(u=u.where("branch_id","=",t));const m=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-h;if(!m||m.length===0)return[];if(p>100){const b=m.reduce((w,N)=>w+(N.files?JSON.stringify(N.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${m.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return m.map(w=>({...w,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Ut);const f=m.map(b=>b.id),[y,g,x]=await Promise.all([Od(f),Fd(f),zd(f)]);return m.map(b=>{const w=b.branch_id?y.get(b.branch_id):void 0,N=b.merged_branch_id?y.get(b.merged_branch_id):void 0,C=g.get(b.id)||[],S=x.get(b.id)||[];return{...b,branch:w,mergedBranch:N,analyses:C,entities:S}}).map(Ut)}catch(u){return _e("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function ot({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let h=0;h<o.length;h+=50){const u=o.slice(h,h+50),m=await ot({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});m&&d.push(...m)}return d}const c=Me();try{const u=await(i?c.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):c.selectFrom("entities").selectAll("entities")).$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!s,m=>m.where("entities.file_path","in",s)).$if(!!a,m=>m.where("entities.name","in",a)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:s,shas:o}),null):u.map(jn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function Yd(e,t){const{jsonArrayFrom:r}=Jt();let s=e.selectFrom("entity_branches").select(ud);return t&&(s=t(s)),r(s)}async function Go({projectId:e,sha:t}){const r=Me();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>Yd(a,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?jn(s):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&_e("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(s){return _e("CodeYam Error: Load Entity: Database error",s,{projectId:e,sha:t}),null}}const Xr=1e3;async function Ko({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const h=t.slice(d,d+50),u=await Ko({projectId:e,filePaths:h,fileIds:r,fileNames:s});u&&c.push(...u)}return c}const a=Me(),o=[];let i=0;try{for(;;){let c=a.selectFrom("files").selectAll().where("project_id","=",e).limit(Xr).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(s){if(s.length===0)return[];c=c.where("name","in",s)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<Xr))break;i+=Xr}return o==null?void 0:o.map(Ys)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function Bd({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=Me().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return a||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:s}),null;const d=Bs(c);return s&&(d.files=await Ko({projectId:d.id})),r&&(d.branches=await qo({projectId:d.id,includeInactive:!1})),d}catch(o){return a||console.log("CodeYam Error: Error loading project",o),null}}function lr(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=lr(o,a):a!==void 0&&(r[s]=a)}return r}async function Et({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let d=0;d<=4;d++)try{return await Me().transaction().execute(async h=>{var f,y;const u=await h.selectFrom("commits").select(["id","metadata"]).$if(!!e,g=>g.where("id","=",e)).$if(!!t,g=>g.where("sha","=",t)).executeTakeFirst();if(!u)return _e(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const m=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),s.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(f=m.currentRun)==null?void 0:f.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",s.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",a)),r=lr(r??{},{currentRun:s});else if(!r&&!o)return m;const p=r?lr(m,r):m;if(a&&p.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",p.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${p.currentRun.analyzerPid}, capture=${p.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${p.currentRun.analysesCompleted}, captures=${p.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((y=p.historicalRuns)==null?void 0:y.length)||0}`);const g={...p.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(g,null,2)),p.historicalRuns=[...p.historicalRuns||[],g],console.log(`[updateCommitMetadata] Historical runs after archiving: ${p.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(p.historicalRuns.map(x=>({entityShas:x.currentEntityShas,archivedAt:x.archivedAt,completed:{analyses:x.analysesCompleted,captures:x.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(p);try{return await h.updateTable("commits").set({metadata:JSON.stringify(p)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?p:(_e(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),m)}catch(g){return _e(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,g),m}})}catch(h){const u=h instanceof Error&&h.message.includes("database is locked");if(u&&d<4){const m=250*Math.pow(2,d);await new Promise(p=>setTimeout(p,m));continue}return _e(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${d+1} attempts`:""}`,h),null}return null}async function Qo(e,t,r="analysis"){try{return await Me().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return _e(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=xt(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(_e(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return _e(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function an(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await Me().transaction().execute(async i=>{const c=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!c)return _e(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const d=xt(c);return t(d.status,d),await i.updateTable("analyses").set({status:JSON.stringify(d.status)}).where("id","=",e).returningAll().executeTakeFirst()?d.status:(_e(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const c=i instanceof Error&&i.message.includes("database is locked");if(c&&o<4){const d=250*Math.pow(2,o);await new Promise(h=>setTimeout(h,d));continue}return _e(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${c?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function nn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Me().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return _e(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const c=r?lr(i,r):i;s&&await s(c,Bs(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(_e(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return _e(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(a){return _e(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const Ud=()=>crypto.randomUUID();function Wd(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Ud(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function Hd(e){if(e.length===0)return[];const t=Me(),r=e.map(Wd);try{return(await t.insertInto("scenarios").values(r).onConflict(Sr(r[0],"id",["created_at"])).returningAll().execute()).map(Bo)}catch(s){return _e("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const Jd=()=>crypto.randomUUID();function Vd(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??Jd(),commit_id:r,branch_id:s}}async function Ya(e){if(e.length===0)return[];const t=Me(),r=e.map(Vd);try{return(await t.insertInto("commit_branches").values(r).onConflict(Sr(r[0],"id",["created_at"])).returningAll().execute()).map(Us)}catch(s){return _e("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function qd(e,t){const r=Me(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(Sr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return _e("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const Gd=()=>crypto.randomUUID();function Kd(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:h,author:u,metadata:m,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Gd(),project_id:s??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:h}}async function Qd({projectId:e,commits:t}){const r=Me();try{const s=t.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in s)await qd(i,s[i]);const a=t.map(i=>Kd(i,e));return(await r.insertInto("commits").values(a).onConflict(Sr(a[0],"id",["created_at"])).returningAll().execute()).map(Ut)}catch(s){return _e("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const cr=B.join(Do.homedir(),".codeyam","secrets.json"),dr=B.join(process.cwd(),".codeyam","secrets.json");async function Tt(){let e={};try{if(Q.existsSync(dr)){const o=await Ce.readFile(dr,"utf8");e=JSON.parse(o)}}catch{console.warn(sr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(Q.existsSync(cr)){const o=await Ce.readFile(cr,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(sr.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 a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function Zd(e,t=!0){const r=t?cr:dr,s=B.dirname(r);await Ce.mkdir(s,{recursive:!0}),await Ce.writeFile(r,JSON.stringify(e,null,2)),await Ce.chmod(r,384)}function Xd(e=!0){return e?cr:dr}async function Ba(){const e=await Tt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function eu(e){console.log(),console.log(sr.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await xc({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function tu(e=!0){const t=await Ba();if(t.isValid)return t.secrets;const r=await eu(t.missing),a={...await Tt(),...r};await Zd(a,e);const o=Xd(e);return console.log(sr.green(`✓ Configuration saved to ${o}`)),(await Ba()).secrets}function Zo(e=process.cwd()){let t=B.resolve(e);const r=B.parse(t).root;for(;t!==r;){const a=B.join(t,".codeyam","config.json");if(Q.existsSync(a))return t;t=B.dirname(t)}const s=B.join(r,".codeyam","config.json");return Q.existsSync(s)?r:null}let Xo=Zo();function xe(){return Xo}function nu(e){Xo=e}function ei(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const ru={"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>`};ei(ru);const su={"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>`};ei(su);function vn(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 a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=vn(a[i],c,r):o[i]=c}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const c=t[a][i];typeof c=="object"&&c!==null?s[a][i]=vn(o[i],c,r):s[a][i]=c}}else typeof t[a]=="object"&&t[a]!==null?s[a]=vn(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function au({projectId:e,commit:t,branch:r}){var c,d,h,u,m,p,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Ld({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(c=o.sort((g,x)=>{var v,b,w,N;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((N=(w=x.branch.metadata)==null?void 0:w.permanent)==null?void 0:N.order)??999)})[0])==null?void 0:c.branch,s&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=s.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await Ya(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await Ya([a])}function $t(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=xe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return te.join(e,".codeyam","db.sqlite3")}async function We(){const e=await tu();process.env.SQLITE_PATH=$t(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function De(e){await We();const t=await Bd({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await qo({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 ou(e,t,r){await We();const s=xe(),a=_d(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(s)try{if(h=je(`git diff HEAD -- "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=je(`cat "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
|
|
30
|
-
`);h=`@@ -0,0 +1,${m.length} @@
|
|
31
|
-
${m.map(p=>`+${p}`).join(`
|
|
32
|
-
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await Qd({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await au({projectId:e.id,commit:c[0],branch:t}),c[0]}async function Vt(){await We();const e=await ot({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const d of e){const h=`${d.name}::${d.filePath}`,u=t.get(h);(!u||d.createdAt&&u.createdAt&&d.createdAt>u.createdAt)&&t.set(h,d)}const r=[...t.values()],s=e.map(d=>d.sha),a=await Pt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const d of a)o.has(d.entitySha)||o.set(d.entitySha,[]),o.get(d.entitySha).push(d);const i=new Map;for(const d of e){const h=`${d.name}::${d.filePath}`,u=i.get(h)||[];u.push(d.sha),i.set(h,u)}return r.map(d=>{const h=o.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=`${d.name}::${d.filePath}`,m=i.get(u)||[];for(const p of m){if(p===d.sha)continue;const f=o.get(p);if(f&&f.length>0)return{...d,analyses:f}}return{...d,analyses:[]}})}async function kr(e,t){await We();const r=await Pt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Go({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Er(e){if(await We(),e.name&&e.projectId){const r=await Pt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0]}}const t=await Pt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function ti(e){await We();const t=await Pt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Ht(e){await We();const t=await Re();if(!t)return null;const{project:r}=await De(t);return await Go({projectId:r.id,sha:e})}async function ni(e){var s,a,o,i,c,d,h,u;await We();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=p.resolvedFilePath??p.filePath,y=p.resolvedName??p.name;let g=await ot({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&p.resolvedIsDefault&&(g=await ot({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await Pt({entityShas:[x.sha],limit:1});let b,w,N;if(v&&v.length>0&&v[0].scenarios){const C=v[0],S=C.scenarios||[],A=S.length,E=S.find(j=>{var R,M;return(M=(R=j.metadata)==null?void 0:R.screenshotPaths)==null?void 0:M[0]});E&&(b=(o=(a=E.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],w=E.name),N={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||C.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:A,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 N={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:w,analysisStatus:N})}}}if((c=e.metadata)!=null&&c.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const y=e.metadata.importedBy[p][f];y.shas&&m.push(...y.shas)}if(m.length>0){const p=await ot({projectId:e.projectId,shas:m});if(p)for(const f of p){const y=await Pt({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],w=b.scenarios||[],N=w.length,C=w.find(A=>{var E,k;return(k=(E=A.metadata)==null?void 0:E.screenshotPaths)==null?void 0:k[0]});C&&(g=(h=(d=C.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],x=C.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function Re(){try{const e=xe();if(!e)return null;const t=te.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function on(){await We();try{const e=await Re();if(!e)return null;const{project:t,branch:r}=await De(e),s=await ir({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 Ar(){try{const e=xe();if(!e)return null;const t=te.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function ri(e){try{const t=xe();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=te.join(t,e.filePath);return await ye.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function si(e){try{const t=xe();if(!t||!e.filePath)return!1;const r=te.join(t,e.filePath),a=(await ye.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function ai(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 ot({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await Pt({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,c]of a.entries())c.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,c)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=c.analyses[0])==null?void 0:m.createdAt)||c.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function oi(e){try{const t=xe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=te.join(t,".codeyam","config.json"),s=await ye.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await ye.writeFile(r,i,"utf8"),a.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await nn({projectSlug:a.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const iu=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Vt,getAnalysesForEntity:kr,getAnalysisForExactEntitySha:ti,getCurrentCommit:on,getEntityBySha:Ht,getEntityCodeFromFilesystem:ri,getEntityHistory:ai,getLatestAnalysisForEntity:Er,getProjectConfig:Ar,getProjectSlug:Re,getRelatedEntities:ni,hasFileBeenModifiedSinceEntity:si,requireBranchAndProject:De,updateProjectConfig:oi},Symbol.toStringTag,{value:"Module"})),ii="secrets.json";function li(e){return te.join(e,".codeyam",ii)}function ci(){return te.join(xs.homedir(),".codeyam",ii)}async function Pr(e){let t={};try{const r=ci(),s=await ye.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=li(e),s=await ye.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function lu(e,t,r=!0){const s=r?ci():li(e),a=te.dirname(s);await ye.mkdir(a,{recursive:!0}),await ye.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
-
`,"utf-8")}async function cu(e){const t=await Pr(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 du=3;let gn=0;async function Fn(e){if(!e||e.length===0)return[];if(gn>=du)return console.warn(`[Loader] Circuit breaker open (${gn} 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 a=setTimeout(()=>{s||(s=!0,gn++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);ot({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),gn=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),gn++,r([]))})})}function uu({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(kt(t))try{if(dc(t).length>0)return!1;Vr(t,{recursive:!0})}catch{return!1}try{je(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{je(`rm -rf "${Da(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=Da(t,a);kt(o)&&Vr(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(kt(t))try{Vr(t,{recursive:!0})}catch{}return!1}}async function hu({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&uu({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((c,d)=>{const h=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const f of r)m.push(`--exclude=${f}`);m.push(h,u);const p=gt("rsync",m);p.on("exit",f=>{if(f===0){if(!a){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:m},null,2)),d(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{a||console.log("Error occurred:",f),d(f)})})}const mu=Ls(Ds);async function pu(e){return new Promise(t=>setTimeout(t,e))}function fu(e){try{return process.kill(e,0),!0}catch{return!1}}async function di(e){try{const{stdout:t}=await mu(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
-
`).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await di(a);s.push(...o)}return s}catch{return[]}}function Ua(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function gu(e,t,r){const s=await di(e);for(const a of s.reverse())await Ua(a,t,r);await Ua(e,t,r)}async function kn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await gu(e,o,t);for(let c=0;c<i;c++)if(await pu(1e3),s+=1e3,!await fu(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function yu(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ic(),createdAt:t}}wc.config({quiet:!0});var ui=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ui||{});class xu extends Cc{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Nc(),{process:s,type:a,name:o,metadata:i,parentId:c}=t,d={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:s}),c){const m=this.processes.get(c);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const h=(m,p)=>{this.handleProcessExit(r,m,p)},u=m=>{this.handleProcessError(r,m)};return s.on("exit",h),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",h),s.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(c=>this.shutdown(c,r))),o.pid)try{await kn(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.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[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const c=o.process.__cleanup;c&&c(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let es=null;function bu(){return es||(es=new xu),es}const vu={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function wu({command:e,args:t,workingDir:r,outputOptions:s=vu,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},c=gt(e,t,{cwd:r,env:i});return bu().register({process:c,type:ui.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const y=te.join(r,"log.txt");Q.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},p=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
-
`).map(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
|
|
36
|
-
`)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&m(g+`
|
|
37
|
-
`),s.stdoutCallback&&s.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&m(g+`
|
|
38
|
-
`),s.stderrCallback&&s.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function Cu(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 Nu({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
|
|
39
|
-
`);Q.writeFileSync(`${e}/.env`,a);const o=Cu(r);return wu({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const Su="/tmp/codeyam/local-dev";function hi(e){return B.join(Su,e)}function mi(e){return B.join(hi(e),"codeyam")}function it(e){return B.join(hi(e),"project")}function _r(e){return B.join(mi(e),"log.txt")}const ku=[".sync-metadata.json","__codeyamMocks__"];async function Eu(e,t={}){const{port:r,silent:s=!0}=t,a=it(e);if(r)try{je(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{je(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function Au(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=it(e),i=[],c=[];if(!Q.existsSync(o))return{removed:i,errors:c};r&&await Eu(e,{port:s,silent:a});for(const d of ku){const h=B.join(o,d);if(Q.existsSync(h))try{(await Ce.stat(h)).isDirectory()?await Ce.rm(h,{recursive:!0,force:!0}):await Ce.unlink(h),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const Pu=B.dirname(br(import.meta.url));function _u(e){let t=e;for(;t!==B.dirname(t);){const r=B.join(t,"package.json");if(Q.existsSync(r))try{if(JSON.parse(Q.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=B.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function jr(){const e=_u(Pu);return B.join(e,"analyzer-template")}function ln(e){return mi(e)}function ju(){const e=jr();return Q.existsSync(B.join(e,".finalized"))}async function Wa(e){const t=jr(),r=ln(e);if(!Q.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ce.mkdir(B.dirname(r),{recursive:!0}),await hu({sourcePath:t,destinationPath:r,silent:!0})}function cn(e,t,r,s){const a=ln(e);if(!Q.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Nu({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Mu(e){const t=jr(),r=ln(e),s=B.join(t,".build-info.json"),a=B.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(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(Q.readFileSync(s,"utf8")),i=JSON.parse(Q.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Mn(e,t){const r=ln(e);if(!Q.existsSync(r)){t.update("Creating analyzer..."),await Wa(e);return}const s=Mu(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Wa(e))}async function Ws(e){await Au(e,{killProcesses:!1})}const Tu=B.dirname(br(import.meta.url));function Mr(){let e=Tu;for(;e!==B.dirname(e);){const t=B.join(e,"package.json");if(Q.existsSync(t))try{if(JSON.parse(Q.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=B.dirname(e)}return null}function en(e){if(!Q.existsSync(e))return null;try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function $u(){const e=Mr();if(e){const t=[B.join(e,"src/webserver/build-info.json"),B.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=en(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function Iu(){const e=Mr();if(e){const t=B.join(e,"package.json");try{const r=JSON.parse(Q.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const Hs=$u(),ts=Iu();function Js(){if(ts!=="unknown"&&ts!=="0.1.0")return ts;const e=Mr();if(e)for(const t of[B.join(e,"src/webserver/build-info.json"),B.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=en(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function pi(e){const t=Mr();let r=null;if(t){const d=[B.join(t,"src/webserver/build-info.json"),B.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const h of d)if(r=en(h),r)break}const s=jr(),a=B.join(s,".build-info.json"),o=en(a);let i=null;if(e){const d=ln(e),h=B.join(d,".build-info.json");i=en(h)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:Hs,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function Tr(e){const t=ln(e),r=B.join(t,".build-info.json"),s=en(r);return(s==null?void 0:s.version)??null}function fi(){const e=xe();return e?B.join(e,".codeyam","server.json"):null}function gi(){const e=fi();if(!e||!Q.existsSync(e))return null;try{const t=Q.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Ru(){const e=fi();if(e)try{Q.unlinkSync(e)}catch{}}const Du="/assets/globals-BZB_H1w2.css";function Ha({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=_(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(de,{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:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Lu({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[l("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})]}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Ou({serverVersion:e}){const[t,r]=_("stale"),[s,a]=_(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),h):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function dn({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,h]=_(!1),u=ie(()=>{navigator.clipboard.writeText(e).then(()=>{h(!0),setTimeout(()=>h(!1),a)}).catch(m=>{console.error("Failed to copy:",m)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(ct,{size:c,className:"text-green-500"}):n(pt,{size:c}):d?r:t})}function Fu({currentVersion:e,latestVersion:t}){const[r,s]=_(!1);if(r)return null;const a="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:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),l("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),l("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(dn,{content:a,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 yn=null,zn=0;const zu=3600*1e3;function Yu(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function Bu(){const e=Js();if(yn&&Date.now()-zn<zu)return yn;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 c={updateAvailable:!1,latestVersion:null,currentVersion:e};return yn=c,zn=Date.now(),c}const o=(await s.json()).version;if(!o){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return yn=c,zn=Date.now(),c}const i={updateAvailable:Yu(o,e),latestVersion:o,currentVersion:e};return yn=i,zn=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function ur(e){return B.join(e,".codeyam","queue.json")}function wn(e){const t=ur(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 Uu(e,t){const r=ur(e),s=B.dirname(r);Q.existsSync(s)||Q.mkdirSync(s,{recursive:!0});try{Q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const fr=class fr extends vr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=Ae.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||fr.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))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=te.join(this.options.projectRootPath,t),s=te.join(this.options.tmpProjectPath,t);try{if(!Ae.existsSync(r)){Ae.existsSync(s)&&(Ae.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=te.dirname(s);Ae.existsSync(a)||Ae.mkdirSync(a,{recursive:!0}),Ae.copyFileSync(r,s);const o=te.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:te.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}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")}};fr.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let vs=fr,Wu=class extends vr{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 ws="__codeyam_dev_mode_event_emitter__";globalThis[ws]||(globalThis[ws]=new Wu);const Ja=globalThis[ws],Cs=new Map;async function Hu(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Ju(e,t,r);else if(e.type==="baseline")await Vu(e,t,r);else if(e.type==="recapture")await qu(e,t,r);else if(e.type==="capture-only")await Gu(e,t,r);else if(e.type==="debug-setup")await Ku(e,t,r);else if(e.type==="interactive-start")await Qu(e,t,r);else if(e.type==="interactive-stop")await Zu(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 Ju(e,t,r){var g,x,v,b;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await De(s);await Ws(s),await Mn(s,{update:w=>console.log(`[Queue] ${w}`)});const d=Tr(s),h={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((v=c.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:it(s),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=cn(s,h,p),y=w=>{try{return process.kill(w,0),!0}catch{return!1}};await Et({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const w=new Promise((N,C)=>setTimeout(()=>C(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,w]),await Et({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Et({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(N=>setTimeout(N,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await kn(f.process.pid,()=>{})}catch{}}}catch(w){if(console.error(`[Queue] Analysis job ${e.id} failed:`,w),f.process.pid&&y(f.process.pid))try{await kn(f.process.pid,()=>{})}catch{}try{await Et({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:w instanceof Error?w.message:String(w)}}),r==null||r.notifyChange("commit")}catch(N){console.error("[Queue] Failed to update commit metadata after job failure:",N)}throw w}}async function Vu(e,t,r){var p,f,y;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await De(s);await Ws(s),await Mn(s,{update:g=>console.log(`[Queue] ${g}`)});const i=Tr(s),c={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:it(s),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=cn(s,c,h),m=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Et({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await Et({commitSha:a,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(u.process.pid)try{m(u.process.pid)&&await kn(u.process.pid,()=>{})}catch{}}}async function qu(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const c=await bt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-BzAbACSx.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let N={};w!=null&&w.metadata&&(typeof w.metadata=="string"?N=JSON.parse(w.metadata):N=w.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",c.entitySha).execute()}await an(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await De(s);await Mn(s,{update:v=>console.log(`[Queue] ${v}`)});const h=Tr(s),u={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:it(s),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??qe.Next,orchestrateCapture:"local-sequential"},p=cn(s,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Gu(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const c=await bt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-BzAbACSx.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let N={};w!=null&&w.metadata&&(typeof w.metadata=="string"?N=JSON.parse(w.metadata):N=w.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",c.entitySha).execute()}await an(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await De(s);await Mn(s,{update:v=>console.log(`[Queue] ${v}`)});const h=Tr(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:it(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??qe.Next,orchestrateCapture:"local-sequential"},p=cn(s,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Ku(e,t,r){var p,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await bt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await De(s);await Ws(s),await Mn(s,{update:x=>console.log(`[Queue] ${x}`)});const d={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:it(s),port:void 0,noServer:!1,framework:((g=(y=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||qe.Next},m=await cn(s,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function Qu(e,t,r){var x,v,b,w;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await bt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await De(s),d={...await Tt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:$t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h=it(s),u=te.join(h,".next","dev","lock");if(Ae.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const N=je(`pgrep -f ${JSON.stringify(h)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(N)for(const C of N.split(`
|
|
40
|
-
`).filter(Boolean))try{process.kill(parseInt(C,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${C}`)}catch{}}catch{}try{Ae.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const m=Ae.existsSync(h)&&Ae.existsSync(te.join(h,"package.json")),p={packageManager:((x=c.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:h,port:void 0,noServer:!1,fast:m,framework:((w=(b=(v=c.metadata)==null?void 0:v.webapps)==null?void 0:b[0])==null?void 0:w.framework)||qe.Next};await an(a,N=>{N.readyToBeCaptured=!0});const f=cn(s,d,p);await Qo(a,N=>{N.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=it(s),g=new vs({projectRootPath:t,tmpProjectPath:y});g.on("sync",N=>{N.type==="file-synced"?Ja.emitFileSynced(N.fileName,N.filePath):N.type==="error"&&Ja.emitError(N.fileName,N.filePath)}),g.start(),Cs.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Zu(e,t,r){var h;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await bt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(h=o.metadata)==null?void 0:h.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const c=Cs.get(a);c&&(c.stop(),Cs.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const d=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${d}`);try{try{process.kill(d,0)}catch{console.log(`[Queue] Process ${d} already exited`);return}await kn(d,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${d}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${d}:`,u),u}finally{await Qo(a,u=>{u.interactiveMode=null})}}class Xu{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=wn(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||Rs(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,c=>{c?i(c):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}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(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(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 a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),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 Hu(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(){Uu(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class eh{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=ur(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=ur(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=Q.watch(r,(s,a)=>{a==="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 th{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=wn(r)}start(){this.cachedState=wn(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 eh(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,c)=>{r=i,s=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}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=wn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=wn(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 nh(e){const t=B.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 rh(e){try{return process.kill(e,0),!0}catch{return!1}}async function sh(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 ah(e){const t=nh(e);return!t||!rh(t.pid)||!await sh(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class oh extends vr{constructor(){super();Ln(this,"watcher",null);Ln(this,"dbPath",null);Ln(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=$t();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",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${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 _t=new oh;let Yt=null,Cn=null;async function ih(){if(!Yt){if(Cn){await Cn;return}Cn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Zo()||process.cwd();if(nu(e),console.log(`[GlobalQueue] Project root: ${e}`),await We(),process.env.NODE_ENV==="development")try{const r=te.join(e,".codeyam","config.json"),a=JSON.parse(await Ae.promises.readFile(r,"utf8")).projectSlug;a&&(await nn({projectSlug:a,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 ah(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new th(t,e,()=>{_t.notifyChange("unknown")});await r.start(),Yt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Xu(e,_t);await r.start(),Yt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Cn}}async function vt(){return Yt||await ih(),Yt}function lh(){return Yt||(Cn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const ch=()=>[{rel:"stylesheet",href:Du},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],dh={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:Js()};async function uh({request:e,context:t}){var r,s,a,o,i,c,d,h,u,m,p;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=xe()||process.cwd(),[x,v,b]=await Promise.all([Re(),Pr(g),Bu().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:w,branch:N}=await De(x);y();const C=await ir({projectId:w.id,branchId:N.id,limit:20,skipRelations:!0});y();const S=C.length>0?C[0]:null,A=t.analysisQueue||lh(),E=A==null?void 0:A.getState();y();const k=await Promise.all(((E==null?void 0:E.jobs)||[]).map(async G=>{var re;const Z=await Fn(G.entityShas||[]);return Z.length===0&&((re=G.entityShas)!=null&&re.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",G.id),{...G,entities:Z}}));let j=null;if(E!=null&&E.currentlyExecuting){const G=E.currentlyExecuting,Z=await Fn(G.entityShas||[]);Z.length===0&&((r=G.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",G.id),j={...G,entities:Z}}const R=j?k.filter(G=>G.id!==j.id):k;let M=((a=(s=S==null?void 0:S.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(M.length===0){const G=((o=S==null?void 0:S.metadata)==null?void 0:o.historicalRuns)||[];if(G.length>0){const re=[...G].sort((ge,ve)=>{const Ne=ge.archivedAt||ge.createdAt||"";return(ve.archivedAt||ve.createdAt||"").localeCompare(Ne)})[0];if(re){const ge=re.analysisCompletedAt||re.createdAt;if(ge){const ve=new Date(ge).getTime(),Ee=Date.now()-1440*60*1e3;ve>Ee&&(M=re.currentEntityShas||[])}}}}const I=await Fn(M),$=[];v.ANTHROPIC_API_KEY&&$.push("ANTHROPIC_API_KEY"),v.GROQ_API_KEY&&$.push("GROQ_API_KEY"),v.OPENAI_API_KEY&&$.push("OPENAI_API_KEY"),v.OPENROUTER_API_KEY&&$.push("OPENROUTER_API_KEY"),y();const T=[];for(const G of C){const Z=((i=G.metadata)==null?void 0:i.historicalRuns)||[];for(const re of Z)T.push(re)}T.sort((G,Z)=>{const re=G.archivedAt||G.analysisCompletedAt||G.createdAt||"";return(Z.archivedAt||Z.analysisCompletedAt||Z.createdAt||"").localeCompare(re)});const q=new Set(((c=j==null?void 0:j.entities)==null?void 0:c.map(G=>G.sha))||[]),H=T.filter(G=>!(G.currentEntityShas||[]).some(re=>q.has(re))).slice(0,3),U=new Set;for(const G of H)for(const Z of G.currentEntityShas||[])U.add(Z);const F=await Fn(Array.from(U)),L=new Map;for(const G of F)L.set(G.sha,G);const P=H.map(G=>({...G,entities:(G.currentEntityShas||[]).map(Z=>L.get(Z)).filter(Z=>Z!=null)})),O=gi(),z=(O==null?void 0:O.cliVersion)??"unknown",J=z!=="unknown"&&z!==Hs,ee=((h=(d=w.metadata)==null?void 0:d.labs)==null?void 0:h.simulations)??!1,Y=ee?ju():!1,D=((u=w.metadata)==null?void 0:u.editorMode)??!1,W={currentRun:(m=S==null?void 0:S.metadata)==null?void 0:m.currentRun,projectSlug:x,currentEntities:I,availableAPIKeys:$,queuedJobCount:R.length,queueJobs:R,currentlyExecuting:j,historicalRuns:P,isServerOutOfDate:J,serverVersion:z,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((p=w.metadata)==null?void 0:p.labs)??null,simulationsEnabled:ee,isSimulationsReady:Y,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:D,displayVersion:Js()};return V(W)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),V(dh)}}function hh(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:h,npmUpdate:u,labs:m,simulationsEnabled:p,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=Je(),{toasts:v,closeToast:b}=zs(),w=lt(),N=be(w),C=gr();X(()=>{N.current=w},[w]);const S=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/")||C.pathname.startsWith("/editor"),A=C.pathname.includes("/fullscreen")||C.pathname.startsWith("/editor");return X(()=>{const E=new EventSource("/api/events");let k=null,j=0;const R=2e3;return E.addEventListener("message",M=>{const I=JSON.parse(M.data);if(I.type==="queue")N.current.revalidate(),j=Date.now();else if(I.type==="db-change"||I.type==="unknown"){const $=Date.now(),T=$-j;T<R?(k&&clearTimeout(k),k=setTimeout(()=>{N.current.revalidate(),j=Date.now(),k=null},R-T)):(N.current.revalidate(),j=$)}}),E.addEventListener("error",M=>{console.error("SSE connection error:",M)}),()=>{k&&clearTimeout(k),E.close()}},[]),l(ue,{children:[l("div",{className:`min-h-screen ${S?"":"grid"} bg-cygray-10`,style:S?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!S&&n(Hc,{labs:m,isAdmin:y,editorMode:g}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(Ou,{serverVersion:h}),u&&u.currentVersion&&n(Fu,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),p&&s.length===0&&n(Ha,{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"}),p&&!f&&n(Ha,{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(El,{})}),n(Lu,{version:x})]})]}),n(qc,{toasts:v,onClose:b}),!A&&p&&n(Gc,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const mh=Ue(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Cl,{}),n(Nl,{})]}),l("body",{children:[n(Jc,{children:n(Uc,{children:n(hh,{})})}),n(Sl,{}),n(kl,{})]})]})}),ph=Object.freeze(Object.defineProperty({__proto__:null,default:mh,links:ch,loader:uh},Symbol.toStringTag,{value:"Module"}));function Yn(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function qt({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const c=Le(),[d,h]=_(null),[u,m]=_(!1),[p,f]=_(!1),[y,g]=_(!1),x=be(!1),v=be(null),b=be(null),w=be(null),[N,C]=_(0),[S,A]=_(0),E=be(null),k=be(!1),{interactiveUrl:j,resetLogs:R}=yt(a,o),M=be(t),I=be(i);X(()=>{I.current!==i&&(I.current=i,d&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),C(0),A(T=>T+1),k.current=!1,E.current&&(clearTimeout(E.current),E.current=null)))},[i,d]),X(()=>{if(M.current!==t&&(M.current=t,v.current&&b.current&&r)){let T=v.current;if(w.current&&s){const H=Yn(w.current),U=Yn(s);H!==U&&(T=T.replace(H,U),w.current=s)}const q=Yn(b.current),K=Yn(r);T=T.replace(q,K),b.current=r,h(T),f(!0),g(!1),C(0),A(H=>H+1),k.current=!1,E.current&&(clearTimeout(E.current),E.current=null);return}},[t,r,s]),X(()=>{if(j){const T=j+"?width=600px";v.current=T,r&&(b.current=r),s&&(w.current=s),h(T),m(!1),f(!0)}},[j]),X(()=>{const T=q=>{q.data.type==="codeyam-resize"&&(k.current||(k.current=!0,E.current&&(clearTimeout(E.current),E.current=null),C(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[]);const $=()=>{k.current=!1,E.current&&clearTimeout(E.current);const T=300*Math.pow(2,N);E.current=setTimeout(()=>{k.current||(N<2?(C(q=>q+1),A(q=>q+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},T)};return X(()=>{o&&!x.current&&t&&e&&(x.current=!0,m(!0),g(!1),h(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(q){console.error("[useInteractiveMode] Failed to clear log file:",q)}R(),c.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,R,a]),X(()=>{const T=e,q=()=>{if(x.current&&T){const H=new URLSearchParams({action:"stop",analysisId:T});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const U=navigator.sendBeacon("/api/interactive-mode",H);console.log("[useInteractiveMode] sendBeacon result:",U),U||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,keepalive:!0}).catch(F=>console.error("Failed to stop interactive mode:",F)))}},K=()=>{q()};return window.addEventListener("beforeunload",K),()=>{window.removeEventListener("beforeunload",K),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:T}),q()}},[e]),{interactiveServerUrl:d,isStarting:u,isLoading:p,showIframe:y,iframeKey:S,onIframeLoad:$}}const Bn=10,fh=1024;function $r({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=_(null),h=be(null),u=ae(()=>[...s].sort((b,w)=>b.width-w.width),[s]),{fittingPresets:m,overflowPresets:p}=ae(()=>{const b=[],w=[];for(const N of u)N.width<=fh?b.push(N):w.push(N);return w.sort((N,C)=>C.width-N.width),{fittingPresets:b,overflowPresets:w}},[u]),f=ie(b=>{if(!h.current)return null;const w=h.current.getBoundingClientRect(),N=b-w.left,C=w.width,S=C/2,E=(m.length>0?m[m.length-1].width:0)/2,k=S-E,j=S+E,R=p.length>0?(p.length-1)*Bn:0;if(p.length>0){if(N<k){if(N<=R){const I=Math.min(Math.floor(N/Bn),p.length-1);return p[I]}return p[p.length-1]}if(N>j){const I=C-N;if(I<=R){const $=Math.min(Math.floor(I/Bn),p.length-1);return p[$]}return p[p.length-1]}}const M=Math.abs(N-S);for(let I=m.length-1;I>=0;I--){const $=m[I],T=m[I-1],q=$.width/2,K=T?T.width/2:0;if(M<=q&&M>=K)return $}return m[0]||p[p.length-1]||null},[m,p]),y=ie(b=>{const w=f(b.clientX);d(w),a==null||a(w)},[f,a]),g=ie(()=>{d(null),a==null||a(null)},[a]),x=ie(b=>{const w=f(b.clientX);w&&r(w)},[f,r]),v=c||{name:t,width:e};return l("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map(b=>{const w=b.width===e,N=(c==null?void 0:c.name)===b.name,C=b.width/2;return l("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 ${w||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((b,w)=>{const N=w*Bn,C=b.width===e,S=(c==null?void 0:c.name)===b.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${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:`${N}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)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[v.name," - ",v.width,"px"]})})]})}function Ir({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=_(""),[i,c]=_(""),d=()=>{const u=a.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick: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"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&d(),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})]}),l("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 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function Rr(e){const[t,r]=_([]),s=e?`codeyam-custom-sizes-${e}`:null;X(()=>{if(!s||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(s);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[s]);const a=ie(c=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[s]),o=ie((c,d,h)=>{r(u=>{const m=u.findIndex(y=>y.name===c),p={name:c,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],a(f),f})},[a]),i=ie(c=>{r(d=>{const h=d.filter(u=>u.name!==c);return a(h),h})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function jt(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
41
|
-
.loader {
|
|
42
|
-
width: 48px;
|
|
43
|
-
height: 48px;
|
|
44
|
-
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
45
|
-
border-radius: 50%;
|
|
46
|
-
display: inline-block;
|
|
47
|
-
position: relative;
|
|
48
|
-
box-sizing: border-box;
|
|
49
|
-
animation: rotation 1s linear infinite;
|
|
50
|
-
}
|
|
51
|
-
.loader::after {
|
|
52
|
-
content: '';
|
|
53
|
-
box-sizing: border-box;
|
|
54
|
-
position: absolute;
|
|
55
|
-
left: 50%;
|
|
56
|
-
top: 50%;
|
|
57
|
-
transform: translate(-50%, -50%);
|
|
58
|
-
width: 56px;
|
|
59
|
-
height: 56px;
|
|
60
|
-
border-radius: 50%;
|
|
61
|
-
border: 3px solid;
|
|
62
|
-
border-color: #005c75 transparent;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
@keyframes rotation {
|
|
66
|
-
0% {
|
|
67
|
-
transform: rotate(0deg);
|
|
68
|
-
}
|
|
69
|
-
100% {
|
|
70
|
-
transform: rotate(360deg);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
`})]})}const Va=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],gh=80;function rn(){const[e,t]=_(0);return X(()=>{const r=setInterval(()=>{t(s=>(s+1)%Va.length)},gh);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:Va[e]})}async function yh({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw V("Invalid parameters",{status:400});const s=await Ht(t);if(!s)throw V("Entity not found",{status:404});const a=await Er(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw V("Scenario not found",{status:404});const i=await Re();return V({entity:s,scenario:o,analysis:a,projectSlug:i})}const ns=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],xh=Ue(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Je(),o=ft(),[i]=sn(),[c,d]=_(null),[h,u]=_(1440),[m,p]=_({name:"Desktop",width:1440,height:900}),[f,y]=_(!1),[g,x]=_(null),{customSizes:v,addCustomSize:b}=Rr(a),w=ae(()=>[...ns,...v],[v]),{interactiveServerUrl:N,isStarting:C,isLoading:S,showIframe:A,iframeKey:E,onIframeLoad:k}=qt({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:j}=yt(a,C||S),R=()=>{o(`/entity/${t.sha}`)},M=(z,J)=>{u(z);const ee=w.find(D=>D.width===z&&D.height===J);d(ee||null),p({name:(ee==null?void 0:ee.name)||"Custom",width:z,height:J})},I=z=>{d(z),u(z.width),p({name:z.name,width:z.width,height:z.height})},$=z=>{b(z,m.width,m.height??900),y(!1),p(J=>({...J,name:z}))},T=((s==null?void 0:s.scenarios)||[]).filter(z=>{var J;return!((J=z.metadata)!=null&&J.sameAsDefault)}),q=T.findIndex(z=>z.id===(r==null?void 0:r.id)),K=q+1,H=T.length,U=q>0,F=q<T.length-1,L=()=>{if(U){const z=T[q-1],J=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${J}`)}},P=()=>{if(F){const z=T[q+1],J=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${J}`)}},O=C||S||!A;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Cr,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:L,disabled:!U,className:`${U?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[K,"/",H]}),n("button",{onClick:P,disabled:!F,className:`${F?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:R,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ns[ns.length-1].width}px`,width:"100%"},children:n($r,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:I,devicePresets:w,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||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"})})]}),l("select",{value:m.name,onChange:z=>{const J=w.find(ee=>ee.name===z.target.value);J&&I(J)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[w.map(z=>n("option",{value:z.name,children:z.name},z.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:z=>{const J=parseInt(z.target.value,10);!isNaN(J)&&J>0&&M(J,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
74
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
76
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
77
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
78
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:N?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[O&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),j]})]})]})}),n("iframe",{src:N,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:k,style:{opacity:A?1:0}},E)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),j]})]})]})}),f&&n(Ir,{width:m.width,height:m.height??900,onSave:$,onCancel:()=>y(!1)})]})}),bh=Object.freeze(Object.defineProperty({__proto__:null,default:xh,loader:yh},Symbol.toStringTag,{value:"Module"}));function yi({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a}){const[o,i]=_(null),c=be(null);X(()=>{if(!r)return;const m=new EventSource("/api/dev-mode-events");return m.onmessage=p=>{try{const f=JSON.parse(p.data);f.type==="file-synced"&&(i(f.fileName),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{i(null)},5e3))}catch{}},()=>{m.close(),c.current&&clearTimeout(c.current)}},[r]);let d;s?d="error":t?d="starting":e?d="running":d="stopped";const h={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},u={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return l("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[l("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${h[d]}`}),l("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:u[d]})]}),(d==="stopped"||d==="error")&&a&&n("button",{onClick:a,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]"}),o&&l(ue,{children:[l("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"})}),l("span",{className:"text-green-400",children:["Synced: ",o]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),n("span",{className:"text-gray-500",children:"Claude edits auto-sync to preview via HMR"})]})}const vh=`
|
|
79
|
-
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
80
|
-
.xterm.focus, .xterm:focus { outline: none; }
|
|
81
|
-
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
82
|
-
.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; }
|
|
83
|
-
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
84
|
-
.xterm .composition-view.active { display: block; }
|
|
85
|
-
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
86
|
-
.xterm .xterm-screen { position: relative; }
|
|
87
|
-
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
88
|
-
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
89
|
-
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
90
|
-
.xterm.enable-mouse-events { cursor: default; }
|
|
91
|
-
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
92
|
-
.xterm.column-select.focus { cursor: crosshair; }
|
|
93
|
-
.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; }
|
|
94
|
-
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
95
|
-
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
96
|
-
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
97
|
-
.xterm-dim { opacity: 1 !important; }
|
|
98
|
-
.xterm-underline-1 { text-decoration: underline; }
|
|
99
|
-
.xterm-underline-2 { text-decoration: double underline; }
|
|
100
|
-
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
101
|
-
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
102
|
-
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
103
|
-
.xterm-overline { text-decoration: overline; }
|
|
104
|
-
.xterm-strikethrough { text-decoration: line-through; }
|
|
105
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
106
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
107
|
-
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
108
|
-
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
109
|
-
`;function wh(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=vh,document.head.appendChild(e)}const xi=Ml(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:c,projectSlug:d,onRefreshPreview:h,editorMode:u,onIdleChange:m,notificationsEnabled:p},f){const y=be(null),g=be(null),x=be(null),v=be(null),b=be(null),w=be(!1),N=be(0),C=be(!1),S=be(m);S.current=m;const A=be(p);A.current=p;const E=ie(()=>{var k;(k=x.current)==null||k.focus()},[]);return Tl(f,()=>({sendInput(k){const j=v.current;j&&j.readyState===WebSocket.OPEN&&(j.send(JSON.stringify({type:"input",data:k})),setTimeout(()=>{j.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var k;(k=x.current)==null||k.focus()},scrollToBottom(){var j;const k=(j=y.current)==null?void 0:j.querySelector(".xterm-viewport");k&&(k.scrollTop=k.scrollHeight)}})),X(()=>{const k=y.current;if(!k)return;let j=!1;return wh(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([R,M,I])=>{if(j)return;const $=new R.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(P,O){try{const z=new URL(O),J=z.searchParams.get("scenario");if(J&&z.pathname==="/editor"){const ee=new BroadcastChannel("codeyam-editor");ee.postMessage({type:"switch-scenario",scenarioId:J}),ee.close();return}}catch{}window.open(O,"_blank")}}}),T=new M.FitAddon;$.loadAddon(T),$.loadAddon(new I.WebLinksAddon),$.open(k),T.fit(),x.current=$,$.focus(),setTimeout(()=>$.focus(),100),setTimeout(()=>$.focus(),500);const q=window.location.protocol==="https:"?"wss:":"ws:",K=window.location.host;function H(P){const O=new URLSearchParams;return O.set("entityName",t),r&&O.set("entityType",r),s&&O.set("entitySha",s),a&&O.set("entityFilePath",a),o&&O.set("scenarioName",o),i&&O.set("scenarioDescription",i),c&&O.set("analysisId",c),d&&O.set("projectSlug",d),u&&O.set("editorMode","true"),P&&O.set("reconnectId",P),`${q}//${K}/ws/terminal?${O.toString()}`}function U(P){const O=H(P),z=new WebSocket(O);v.current=z,z.onopen=()=>{N.current=0,C.current=!1,z.send(JSON.stringify({type:"resize",cols:$.cols,rows:$.rows}))},z.onmessage=J=>{var ee,Y;try{const D=JSON.parse(J.data);if(D.type==="session-id"){b.current=D.sessionId;return}if(D.type==="refresh-preview"){h==null||h();return}if(D.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",A.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(ee=S.current)==null||ee.call(S,!0),A.current&&typeof Notification<"u"&&Notification.permission==="granted"){const W=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});W.onclick=()=>{window.focus(),W.close()}}return}D.type==="output"&&($.write(D.data),(Y=S.current)==null||Y.call(S,!1))}catch{$.write(J.data)}},z.onclose=()=>{if(w.current){$.write(`\r
|
|
110
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
111
|
-
`);return}const J=N.current;if(J<5&&b.current){const ee=1e3*Math.pow(2,Math.min(J,3));N.current=J+1,$.write(`\r
|
|
112
|
-
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
113
|
-
`),setTimeout(()=>{w.current||U(b.current)},ee)}else C.current?$.write(`\r
|
|
114
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
115
|
-
`):(C.current=!0,$.write(`\r
|
|
116
|
-
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
117
|
-
`),b.current=null,N.current=0,U())},z.onerror=()=>{}}U(),$.onData(P=>{const O=v.current;O&&O.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"input",data:P}))});let F=null;const L=new ResizeObserver(()=>{F&&clearTimeout(F),F=setTimeout(()=>{const P=T.proposeDimensions();if(!P||P.cols===$.cols&&P.rows===$.rows)return;const O=k.querySelector(".xterm-viewport");let z,J=!0;O&&(z=O.scrollTop,J=O.scrollTop+O.clientHeight>=O.scrollHeight-10),T.fit(),O&&z!==void 0&&(J?O.scrollTop=O.scrollHeight:O.scrollTop=z);const ee=v.current;ee&&ee.readyState===WebSocket.OPEN&&ee.send(JSON.stringify({type:"resize",cols:$.cols,rows:$.rows}))},150)});L.observe(k),g.current=()=>{var P;F&&clearTimeout(F),L.disconnect(),w.current=!0,(P=v.current)==null||P.close(),v.current=null,$.dispose(),x.current=null}}),()=>{var R;j=!0,(R=g.current)==null||R.call(g),g.current=null}},[]),n("div",{ref:y,onClick:E,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function Ve({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=_("loading"),[c,d]=_(!1),h=be(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return X(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:h,src:u,alt:r,onLoad:m,onError:p,className:s||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&l("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Ch({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=ft();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(o=>{var d,h;const i=o.id===t,c=(h=(d=o.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0];return l("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.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(Ve,{screenshotPath:c,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),l("div",{className:"p-2.5 min-w-0 flex-1",children:[l("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]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}async function Nh({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw V("Invalid parameters",{status:400});const s=await Ht(t);if(!s)throw V("Entity not found",{status:404});const a=await Er(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw V("Scenario not found",{status:404});const i=await Re();return V({entity:s,scenario:o,analysis:a,projectSlug:i})}const rs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Sh=Ue(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Je(),o=ft(),i=be(null),c=be(null),[d,h]=_(null),[u,m]=_(1440),[p,f]=_({name:"Desktop",width:1440,height:900}),[y,g]=_(!1),[x,v]=_(null),[b,w]=_("chat"),[N,C]=_(0),S=ie(()=>{C(Z=>Z+1)},[]),{customSizes:A,addCustomSize:E}=Rr(a),k=ae(()=>[...rs,...A],[A]),{interactiveServerUrl:j,isStarting:R,isLoading:M,showIframe:I,iframeKey:$,onIframeLoad:T}=qt({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:N}),{lastLine:q}=yt(a,R||M),K=()=>{o(`/entity/${t.sha}`)},H=(Z,re)=>{m(Z);const ge=k.find(Ne=>Ne.width===Z&&Ne.height===re);h(ge||null),f({name:(ge==null?void 0:ge.name)||"Custom",width:Z,height:re})},U=Z=>{h(Z),m(Z.width),f({name:Z.name,width:Z.width,height:Z.height})},F=Z=>{E(Z,p.width,p.height??900),g(!1),f(re=>({...re,name:Z}))},L=()=>{var re;w("chat"),(re=c.current)==null||re.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.")},P=((s==null?void 0:s.scenarios)||[]).filter(Z=>{var re;return!((re=Z.metadata)!=null&&re.sameAsDefault)}),O=P.findIndex(Z=>Z.id===(r==null?void 0:r.id)),z=O+1,J=P.length,ee=O>0,Y=O<P.length-1,D=()=>{if(ee){const Z=P[O-1];o(`/entity/${t.sha}/scenarios/${Z.id}/dev`)}},W=()=>{if(Y){const Z=P[O+1];o(`/entity/${t.sha}/scenarios/${Z.id}/dev`)}},G=R||M||!I;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Cr,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:D,disabled:!ee,className:`${ee?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[z,"/",J]}),n("button",{onClick:W,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("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:K,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"})})})]}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${rs[rs.length-1].width}px`,width:"100%"},children:n($r,{currentViewportWidth:u,currentPresetName:p.name,onDevicePresetClick:U,devicePresets:k,hideLabel:!0,onHoverChange:v,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||p.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:p.name,onChange:Z=>{const re=k.find(ge=>ge.name===Z.target.value);re&&U(re)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[k.map(Z=>n("option",{value:Z.name,children:Z.name},Z.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:Z=>{const re=parseInt(Z.target.value,10);!isNaN(re)&&re>0&&H(re,p.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"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:p.height??900}),p.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:`
|
|
118
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
119
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
120
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
121
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
122
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:j?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[G&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"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"}),q&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),q]})]})]})}),n("iframe",{ref:i,src:j,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:T,style:{opacity:I?1:0}},$)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting 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"}),q&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),q]})]})]})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>w("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",b==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>w("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",b==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),b==="chat"&&n("button",{onClick:L,disabled:!j,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:b==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(xi,{ref:c,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:a,onRefreshPreview:S})}),b==="scenarios"&&n(Ch,{scenarios:P,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(yi,{serverUrl:j,isStarting:R,projectSlug:a}),y&&n(Ir,{width:p.width,height:p.height??900,onSave:F,onCancel:()=>g(!1)})]})}),kh=Object.freeze(Object.defineProperty({__proto__:null,default:Sh,loader:Nh},Symbol.toStringTag,{value:"Module"}));async function Eh({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:a,viewportHeight:o}=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(),c=B.join(i,".codeyam","journal","screenshots");await Ce.mkdir(c,{recursive:!0});const d=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),h=B.join(c,`${d}.png`),u=B.dirname(new URL(import.meta.url).pathname);let m=u;for(let v=0;v<5;v++){const b=B.dirname(m);if(B.basename(b)==="webserver"||B.basename(m)==="webserver"){m=B.basename(m)==="webserver"?m:b;break}m=b}const p=[B.join(m,"scripts","journalCapture.ts"),B.join(m,"app","lib","journalCapture.ts"),B.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),B.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of p)try{await Ce.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${p.join(", ")}`),f=p[0]);const y=JSON.stringify({url:r,outputPath:h,viewportWidth:a,viewportHeight:o}),g=await new Promise(v=>{const b=gt("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let w="",N="";b.stdout.on("data",C=>{w+=C.toString()}),b.stderr.on("data",C=>{N+=C.toString()}),b.on("close",C=>{v(C===0?{success:!0,output:w}:{success:!1,output:w,error:N||`Process exited with code ${C}`})}),b.on("error",C=>{v({success:!1,output:"",error:C.message})})});if(!g.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:g.error}),{status:500,headers:{"Content-Type":"application/json"}});const x=`screenshots/${d}.png`;return new Response(JSON.stringify({success:!0,path:x}),{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 Ah=Object.freeze(Object.defineProperty({__proto__:null,action:Eh},Symbol.toStringTag,{value:"Module"})),bi=Ts({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Vs=()=>{const e=yr(bi);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Dr=({children:e})=>{const[t,r]=_({height:720,width:1200}),[s,a]=_(1),[o,i]=_(1200),c=be(null),d=ie(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),h=ie(m=>{a(m)},[]),u=ie(m=>{i(m)},[]);return n(bi.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:s,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},Ph=typeof window<"u";function _h(){const[e,t]=_(null);return X(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const jh=1200,Mh=720,qa=30,Th=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const h=_h(),[u,m]=_(!1),[p,f]=_(!1),[y,g]=_(jh),[x,v]=_(Mh),[b,w]=_(null),[N,C]=_(null),{dimensions:S,updateDimensions:A,iframeRef:E,updateScale:k,updateMaxWidth:j}=Vs(),R=ae(()=>Math.min(1,y/S.width),[y,S.width]),M=N!==null?N:R;X(()=>{u||(k(M),c==null||c(M))},[M,k,c,u]),X(()=>{j(y)},[y,j]);const I=ie(()=>{m(!0),C(R)},[R]),$=ie(()=>{m(!1),C(null)},[]),T=ie((F,L)=>{const P=N!==null?N:1,O=Math.round(L.size.width/P);A({width:O}),d==null||d(O,S.height)},[A,N,d,S.height]),q=ie(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);X(()=>{const F=L=>{if(L.data.type==="codeyam-resize"){if(t&&L.data.name!==t||S.height===L.data.height||L.data.height===0)return;A({height:L.data.height})}};return window.addEventListener("message",F),()=>{window.removeEventListener("message",F)}},[E,t,s,S,A]),X(()=>{p&&o&&o(E.current)},[p,o,E]),X(()=>{if(!t)return;const F=setInterval(()=>{var L,P;(P=(L=E==null?void 0:E.current)==null?void 0:L.contentWindow)==null||P.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(F)},[t,E]),X(()=>{const F=()=>{const L=document.getElementById("scenario-container");if(!L)return;const P=L.getBoundingClientRect(),O=L.clientWidth-qa*2,z=window.innerHeight-P.top-qa*2,J=Math.max(z,400),ee=window.innerHeight-P.top;g(O),v(J),w(ee)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),X(()=>{A({width:s,height:a})},[s,a,A]);const K=ae(()=>S.width*M,[S.width,M]),H=ae(()=>{const F=S.height,L=F*M;return F&&F!==720&&F!==900&&L<x?L:x},[S.height,x,M]),U=ie(()=>{window.history.back()},[]);return!Ph||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
123
|
-
.react-resizable-handle-e {
|
|
124
|
-
display: flex !important;
|
|
125
|
-
align-items: center !important;
|
|
126
|
-
justify-content: center !important;
|
|
127
|
-
width: 6px !important;
|
|
128
|
-
height: 48px !important;
|
|
129
|
-
right: -8px !important;
|
|
130
|
-
top: 50% !important;
|
|
131
|
-
transform: translateY(-50%) !important;
|
|
132
|
-
cursor: ew-resize !important;
|
|
133
|
-
background: #d1d5db !important;
|
|
134
|
-
border-radius: 3px !important;
|
|
135
|
-
opacity: 0 !important;
|
|
136
|
-
transition: all 0.2s ease !important;
|
|
137
|
-
}
|
|
138
|
-
.react-resizable-handle-e:hover {
|
|
139
|
-
opacity: 0.8 !important;
|
|
140
|
-
background: #9ca3af !important;
|
|
141
|
-
}
|
|
142
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
143
|
-
opacity: 0.4 !important;
|
|
144
|
-
}
|
|
145
|
-
`}),n(h,{width:K,height:H,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:I,onResizeStop:$,onResize:T,children:n("div",{className:"overflow-auto",style:{width:`${K}px`,height:`${H}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${M})`,transformOrigin:"top left"},children:r?n("iframe",{ref:E,className:"w-full h-full rounded-lg",src:r,onLoad:q,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:U,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function $h({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[h,u]=_(!1),[m,p]=_(String(r)),[f,y]=_(String(s)),[g,x]=_(!1),[v,b]=_(!1),w=be(null);X(()=>{g||p(String(r))},[r,g]),X(()=>{v||y(String(s))},[s,v]),X(()=>{const M=I=>{w.current&&!w.current.contains(I.target)&&u(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[]);const N=ae(()=>{const M=e.find($=>$.width===r&&$.height===s);if(M)return M.name;const I=t.find($=>$.width===r&&$.height===s);return I?I.name:"Custom"},[e,t,r,s]),C=N==="Custom",S=M=>{o(M.width,M.height),u(!1)},A=M=>{const I=M.target.value;p(I);const $=parseInt(I,10);!isNaN($)&&$>0&&o($,s)},E=M=>{const I=M.target.value;y(I);const $=parseInt(I,10);!isNaN($)&&$>0&&o(r,$)},k=()=>{x(!1);const M=parseInt(m,10);(isNaN(M)||M<=0)&&p(String(r))},j=()=>{b(!1);const M=parseInt(f,10);(isNaN(M)||M<=0)&&y(String(s))},R=M=>{(M.key==="Enter"||M.key==="Escape")&&M.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:w,children:[l("button",{onClick:()=>u(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:N}),n("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(M=>l("button",{onClick:()=>S(M),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${N===M.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:M.name}),l("span",{className:"text-xs text-gray-500",children:[M.width," x ",M.height]})]},M.name))]}),t.length>0&&l(ue,{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((M,I)=>M.width-I.width).map(M=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===M.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>S(M),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:M.name}),l("span",{className:"text-xs text-gray-500",children:[M.width," x ",M.height]})]}),c&&n("button",{onClick:I=>{I.stopPropagation(),N===M.name&&e.length>0&&o(e[0].width,e[0].height),c(M.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"})})})]},M.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:A,onFocus:()=>x(!0),onBlur:k,onKeyDown:R,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:E,onFocus:()=>b(!0),onBlur:j,onKeyDown:R,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"})]}),a!==void 0&&a<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*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 ss(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 Ns(e){return e&&(typeof e=="object"||Array.isArray(e))}function Ih(e){return Array.isArray(e)?e.length:void 0}function Rh(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=Ns(t[a]),c=Ns(t[o]);return i&&!c?1:!i&&c?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function Dh({scenarioFormData:e,handleInputChange:t}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Lh({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=ie(()=>{a&&a(e)},[a,e]);return l("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var vi=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(vi||{});const Oh=({name:e,value:t,options:r,onChange:s})=>{const a=ie(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},Fh=({name:e,value:t,onChange:r})=>{const s=ie(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
146
|
-
bg-gray-300 checked:bg-blue-600
|
|
147
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
148
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
149
|
-
checked:after:translate-x-4`})})};function zh({dataType:e,path:t,value:r,onChange:s}){const a=ae(()=>t[t.length-1],[t]),o=ae(()=>t.join("-"),[t]),i=ie(d=>{s(t,d.target.value)},[s,t]),c=ie(d=>{s(t,d.target.value)},[s,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(Oh,{name:o,value:r,options:e.split("|"),onChange:i}):e===vi.BOOLEAN?n(Fh,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Yh({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=_(!1),[c,d]=_(""),h=ie(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(x=>x.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Nr),f=await a(c,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,v)=>{const b=Object.assign({},x);return g(x)&&g(v)&&Object.keys(v).forEach(w=>{g(v[w])?w in x?b[w]=y(x[w],v[w]):Object.assign(b,{[w]:v[w]}):Object.assign(b,{[w]:v[w]})}),b},g=x=>x&&typeof x=="object"&&!Array.isArray(x);m.metadata.data=y(y((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),s(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,c,r,t,s,a]),u=ie(m=>{d(m.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?l(ue,{children:[l("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Bh({namedPath:e,path:t,last:r,onClick:s}){const a=ie(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function Uh({dataItem:e,onClick:t}){const r=ie(()=>t([]),[t]),s=ae(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>l("div",{className:"flex items-center gap-1",children:[n(Bh,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+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-${a}-${o+s}`))]})}function Ga({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=ae(()=>r.data,[r]),h=ae(()=>Rh(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Uh,{dataItem:r,onClick:s}),l("div",{className:"flex flex-col gap-3",children:[n(Yh,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(Ns(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(Lh,{path:g,namedPath:x,isArray:Array.isArray(d),count:Ih(d[u]),onClick:s},`data-${u}-${m}`)}if(u==="id")return null;const p=[...r.path,u];return n(zh,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:a},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:c!=null&&c.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function Ka({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=_(r),c=[];return s&&c.push("border-t"),a&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const Wh=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:h})=>{const u=ie((A,E)=>{const k=Object.assign({},A),j=R=>R&&typeof R=="object"&&!Array.isArray(R);return j(A)&&j(E)&&Object.keys(E).forEach(R=>{j(E[R])?R in A?k[R]=u(A[R],E[R]):Object.assign(k,{[R]:E[R]}):Object.assign(k,{[R]:E[R]})}),k},[]),[m,p]=_({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=_(null),g=ae(()=>({...m.data}),[m]),x=ae(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=ae(()=>{const A={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(A).reduce((E,k)=>{if(k.includes(".")){const[j,R]=k.split(".");E[j]||(E[j]={}),E[j][R]=A[k]}else E[k]=A[k];return E},{})},[r]),b=ie(async A=>{A.preventDefault();const E=A.target.querySelector('input[name="recapture"]'),k=(E==null?void 0:E.value)==="true",j={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:k,dataToSave:j,rawFormData:m.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(j,null,2).substring(0,1e3));const R=s==null?void 0:s.scenarios.map(M=>!a&&M.name===e.name?{...M,name:m.name,description:m.description,metadata:{...M.metadata,data:j}}:M);a&&R.push({name:m.name,description:m.description,metadata:{data:j,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",R),o&&await o(R,{recapture:k}),i&&i(m.name)},[s,e.name,m,g,a,o,i]),w=ie(A=>{p(E=>({...E,[A.target.name]:A.target.value}))},[]),N=ie(A=>{y(E=>{if(!E)return null;for(const k of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let j=k;for(const R of E.path)if(j=ss(j,R),!j)break;j&&(E.data=j)}return{...E}}),p({name:A.name,description:A.description,data:A.metadata.data})},[]),C=ie((A,E)=>{p(k=>{for(const j of[{"Function Arguments":k.data.argumentsData},{"Retrieved Data":k.data.mockData}]){let R=j;for(const M of A.slice(0,-1))if(R=ss(R,M),!R)break;if(R){const M=R[A[A.length-1]];y(I=>I?(I.namedPath[I.namedPath.length-1]===M&&(I.namedPath[I.namedPath.length-1]=E.toString()),I.data[A[A.length-1]]=E,{...I}):null),R[A[A.length-1]]=E}}return{...k}})},[]),S=ie(A=>{var R,M,I;if(A.length===0){y(null);return}let E=x;const k=[];let j=v;for(const $ of A){if(k.push(isNaN(parseInt($))?$:((R=E[$])==null?void 0:R.name)??((M=E[$])==null?void 0:M.title)??((I=E[$])==null?void 0:I.id)??$),E=ss(E,$),!E){console.log("Data not found",E,$),y(null);return}Array.isArray(j)?j=j[0]:j=j[$]}y({path:A,namedPath:k,data:E,structure:j})},[x,v]);return X(()=>{const A=E=>{var k;E.data.type==="codeyam-log"&&((k=E.data.data)!=null&&k.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",E.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),X(()=>{var A;if((A=c==null?void 0:c.current)!=null&&A.contentWindow){const E={arguments:g.argumentsData??[],...g.mockData??{}},k={type:"codeyam-override-data",name:e.name,data:JSON.stringify(E)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:k.type,name:k.name,dataPreview:JSON.stringify(E).substring(0,200)+"...",fullData:E}),c.current.contentWindow.postMessage(k,"*")}},[g,e,c]),n("form",{method:"post",onSubmit:A=>void b(A),children:f?n(Ga,{analysis:s,scenarioName:m.name,dataItem:f,onClick:S,onChange:C,onAIResult:N,onGenerateData:d,saveFeedback:h}):l(ue,{children:[n(Ka,{title:"Edit Name and Description",borderT:!0,children:n(Dh,{scenarioFormData:m,handleInputChange:w})}),e.metadata.data&&n(Ka,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Ga,{analysis:s,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:S,onChange:C,onAIResult:N,onGenerateData:d,saveFeedback:h})})]})})};function Lr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:y}=yt(u??null,s||a);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Th,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:h},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(rn,{}),y]})]})]})})}const Hh=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Jh({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await kr(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(d=a.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(h=a.scenarios)==null?void 0:h.find(u=>u.name===Nr),c=await Re();return V({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function Vh(){var $,T,q;const e=Je(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=ft(),{iframeRef:c}=Vs(),[d,h]=_(!1),[u,m]=_(null),[p,f]=_(null),[y,g]=_(!1),[x,v]=_(!1),[b,w]=_(null),{interactiveServerUrl:N,isStarting:C,isLoading:S,showIframe:A,iframeKey:E,onIframeLoad:k}=qt({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),j=ie(async(K,H)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",H),console.log("[EditScenario] Scenarios to save:",K);try{const U={analysis:t,scenarios:K};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:K.length,scenarioNames:K.map(P=>P.name)});const F=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)}),L=await F.json();if(console.log("[EditScenario] API response:",L),!F.ok||!L.success)throw new Error(L.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),H!=null&&H.recapture&&r.id&&N){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:N}),m("Changes saved. Capturing screenshot...");const P={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",P);const O=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});console.log("[EditScenario] Capture response status:",O.status);const z=await O.json();if(console.log("[EditScenario] Capture response body:",z),!O.ok||!z.success)throw console.error("[EditScenario] Capture failed:",z),new Error(z.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",z),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(H!=null&&H.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const P=new FormData;P.append("analysisId",t.id||""),P.append("scenarioId",r.id||"");const O=await fetch("/api/recapture-scenario",{method:"POST",body:P}),z=await O.json();if(!O.ok||!z.success)throw new Error(z.error||"Failed to trigger recapture");console.log("Recapture queued:",z),f(z.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(U){console.error("Error saving scenarios:",U),m(`Error: ${U instanceof Error?U.message:String(U)}`)}finally{h(!1)}},[t,r.id,N]),R=ie(K=>{},[]),M=ie(async(K,H)=>{var L;const U=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:K,existingScenarios:t.scenarios,scenariosDataStructure:(L=t.metadata)==null?void 0:L.scenariosDataStructure,editingMockName:r.name,editingMockData:H==null?void 0:H.data})}),F=await U.json();if(!U.ok||!F.success)throw new Error(F.error||"Failed to generate scenario data");return F.data},[t,r.name]),I=ie(async()=>{var K;if(!r.id){w("Cannot delete scenario without ID");return}g(!0),w(null);try{const H=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((K=r.metadata)==null?void 0:K.screenshotPaths)||[]})}),U=await H.json();if(!H.ok||!U.success)throw new Error(U.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(H){console.error("[EditScenario] Error deleting scenario:",H),w(H instanceof Error?H.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,($=r.metadata)==null?void 0:$.screenshotPaths,a,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:l(de,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(T=t.entity)==null?void 0:T.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Wh,{currentScenario:r,defaultScenario:s,dataStructure:((q=t.metadata)==null?void 0:q.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:j,onNavigate:R,iframeRef:c,onGenerateData:M,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(de,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void I(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>v(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Lr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:C,isLoading:S,showIframe:A,iframeKey:E,onIframeLoad:k,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const qh=Ue(function(){return n(Dr,{children:n(Vh,{})})}),Gh=Object.freeze(Object.defineProperty({__proto__:null,default:qh,loader:Jh,meta:Hh},Symbol.toStringTag,{value:"Module"})),wi="__codeyam_editor_proxy__",Kh=500;let mt={data:null,timestamp:0};function Ci(){return globalThis[wi]??null}function Ni(e){globalThis[wi]=e}function Si(){const e=Ci();return e?`http://localhost:${e.port}`:null}function Qh(){const e=Date.now();if(mt.data!==null&&e-mt.timestamp<Kh)return mt.data;const t=xe()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=te.join(t,".codeyam","active-scenario.json");try{if(!Ae.existsSync(r))return mt={data:null,timestamp:e},null;const a=JSON.parse(Ae.readFileSync(r,"utf-8")).scenarioId;if(!a)return mt={data:null,timestamp:e},null;const o=te.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!Ae.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),mt={data:null,timestamp:e},null;const i=JSON.parse(Ae.readFileSync(o,"utf-8"));return mt={data:i,timestamp:e},i}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),mt={data:null,timestamp:e},null}}function Zh(e,t){const r=t.routes;if(r&&typeof r=="object"){const a=r[e];if(a&&typeof a=="object"){const o=a;return{body:o.body??a,status:typeof o.status=="number"?o.status:200}}}const s=e.match(/^\/api\/(.+)$/);if(s){const a=s[1];if(a in t&&a!=="routes")return{body:t[a],status:200}}return null}function Xh(e,t,r){const s=new URL(r),a={hostname:s.hostname,port:s.port,path:e.url,method:e.method,headers:{...e.headers,host:`${s.hostname}:${s.port}`}},o=Lo.request(a,i=>{t.writeHead(i.statusCode||200,i.headers),i.pipe(t,{end:!0})});o.on("error",i=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${i.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(o,{end:!0})}function em(e,t,r,s){const a=new URL(s),o=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a.hostname}:${o}`);const i=Sc.connect(o,a.hostname,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
150
|
-
`,d=Object.entries(e.headers).filter(([,h])=>h!=null).map(([h,u])=>`${h}: ${Array.isArray(u)?u.join(", "):u}`).join(`\r
|
|
151
|
-
`);i.write(c+d+`\r
|
|
152
|
-
\r
|
|
153
|
-
`),r.length>0&&i.write(r),i.pipe(t,{end:!0}),t.pipe(i,{end:!0})});i.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{i.destroy()})}async function ki(e){await Ei();const{targetUrl:t}=e;let r=e.port;console.log(`[editorProxy] Starting proxy (requested port ${r}, target ${t})`);const s=Lo.createServer((o,i)=>{const d=new URL(o.url||"/",`http://localhost:${r}`).pathname;if(o.method==="GET"){const h=Qh();if(h){const u=Zh(d,h);if(u){console.log(`[editorProxy] Intercepted ${o.method} ${d} → scenario data (status ${u.status})`),i.writeHead(u.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),i.end(JSON.stringify(u.body));return}}}Xh(o,i,t)});s.on("upgrade",(o,i,c)=>{em(o,i,c,t)});const a=10;for(let o=0;o<a;o++){const i=r+o;try{return await new Promise((d,h)=>{s.once("error",h),s.listen(i,"0.0.0.0",()=>{s.removeListener("error",h),d()})}),r=i,Ni({server:s,port:r,targetUrl:t}),console.log(`[editorProxy] Proxy started on port ${r}, forwarding to ${t}`),{port:r}}catch(c){if((c==null?void 0:c.code)==="EADDRINUSE"&&o<a-1){console.log(`[editorProxy] Port ${i} in use, trying ${i+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",c),null}}return null}async function Ei(){const e=Ci();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Ni(null),setTimeout(t,2e3)})}function Ai(){mt={data:null,timestamp:0}}async function tm(){const e=Si();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);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${r+1}, target ${t.url})`);const s=await ki({port:r+1,targetUrl:t.url});if(s){const a=`http://localhost:${s.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}function Pi(e){const t=[];for(const r of e.split(`
|
|
154
|
-
`))r.includes("[JournalCapture] Page console.error:")?t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,"")):r.includes("[JournalCapture] Network failed:")&&t.push(r.replace(/.*\[JournalCapture\] /,""));return t}async function _i(e,t,r,s){const a=B.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await Ce.readFile(a,"utf8");o=JSON.parse(i)}catch{}o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await Ce.mkdir(B.dirname(a),{recursive:!0}),await Ce.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function nm(e){const t=B.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Ce.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function rm(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function sm(e){const t=B.dirname(new URL(import.meta.url).pathname);let r=t;for(let a=0;a<5;a++){const o=B.dirname(r);if(B.basename(o)==="webserver"||B.basename(r)==="webserver"){r=B.basename(r)==="webserver"?r:o;break}r=o}const s=[B.join(r,"scripts","journalCapture.ts"),B.join(r,"app","lib","journalCapture.ts"),B.join(e,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),B.resolve(t,"..","lib","journalCapture.ts")];for(const a of s)try{return await Ce.access(a),a}catch{}return console.warn(`[editor-register-scenario] journalCapture.ts not found in any of: ${s.join(", ")}`),s[0]}function am(e,t,r){return new Promise(s=>{const a=gt("npx",["tsx",e,t],{cwd:r,env:{...process.env}});let o="",i="";a.stdout.on("data",c=>{o+=c.toString()}),a.stderr.on("data",c=>{i+=c.toString()}),a.on("close",c=>{s(c===0?{success:!0,output:o}:{success:!1,output:o,error:i||`Process exited with code ${c}`})}),a.on("error",c=>{s({success:!1,output:"",error:c.message})})})}async function om({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{name:r,description:s,componentName:a,componentPath:o}=t;if(!r)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Re();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await De(i),d=Me(),h=Rs();try{await d.schema.alterTable("editor_scenarios").addColumn("url","varchar").execute()}catch{}await d.insertInto("editor_scenarios").values({id:h,project_id:c.id,name:r,description:s||null,component_name:a||null,component_path:o||null,url:t.url||null}).execute();const u=process.env.CODEYAM_ROOT_PATH||process.cwd();if(t.mockData){const b=B.join(u,".codeyam","editor-scenarios");await Ce.mkdir(b,{recursive:!0}),await Ce.writeFile(B.join(b,`${h}.json`),JSON.stringify(t.mockData,null,2))}_t.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${r}" (id: ${h})`);const m=t.url&&t.url.startsWith("/"),p=!t.url||m?await tm():null,f=rm();let y;m&&p?y=`${p}${t.url}`:t.url?y=t.url:y=p||f,console.log(`[editor-register-scenario] Capture URL resolution: explicit=${t.url||"none"}, isPath=${m}, proxy=${p||"none"}, devServer=${f||"none"} → using ${y||"none"}`);let g=null,x=null,v=[];if(y){const b=r.replace(/[^a-zA-Z0-9_]+/g,"_"),w=B.join(u,".codeyam","active-scenario.json");await Ce.writeFile(w,JSON.stringify({scenarioId:h,scenarioSlug:b,timestamp:new Date().toISOString()})),Ai(),console.log(`[editor-register-scenario] Active scenario set to "${b}" (${h}), cache invalidated`),await new Promise(R=>setTimeout(R,500));const N=B.join(u,".codeyam","editor-scenarios","screenshots");await Ce.mkdir(N,{recursive:!0});const C=B.join(N,`${h}.png`),S=await sm(u);console.log(`[editor-register-scenario] Capture script: ${S}`);const A=JSON.stringify({url:y,outputPath:C,viewportWidth:1280,viewportHeight:720,...a?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Running Playwright capture: url=${y}, output=${C}`);const E=Date.now(),k=await am(S,A,u),j=Date.now()-E;if(console.log(`[editor-register-scenario] Capture ${k.success?"succeeded":"FAILED"} in ${j}ms`),k.success||(console.warn(`[editor-register-scenario] Capture stdout: ${k.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(k.error||"").slice(0,500)}`)),v=Pi(k.output),await _i(u,h,r,v),v.length>0&&console.warn(`[editor-register-scenario] ${v.length} client-side error(s) detected:`,v),k.success){g=`screenshots/${h}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:g}).where("id","=",h).execute(),_t.notifyChange("scenario")}else x=k.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${x}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");return console.log(`[editor-register-scenario] Done: scenario="${r}", screenshot=${g?"captured":"skipped"}`),new Response(JSON.stringify({success:!0,scenario:{id:h,name:r,description:s,componentName:a||null,componentPath:o||null,screenshotPath:g,url:t.url||null},screenshotCaptured:g!==null,captureError:x,clientErrors:v}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-register-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const im=Object.freeze(Object.defineProperty({__proto__:null,action:om},Symbol.toStringTag,{value:"Module"}));function lm({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=ie(i=>t.some(c=>c.flowId===i),[t]),o=ie(i=>{a(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=a(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:c,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((h,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",n("span",{className:"text-gray-400",children:h.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function qs(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),s=new Map;r.forEach(d=>{s.set(d.id,d)});const a=[];t.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(m=>{const p=s.get(m);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),a.push({scenario:d,coveredFlowIds:h})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:a}}function cm(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const dm=({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 um({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await kr(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(c=>c.name===Nr);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Re();return V({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function hm(){var U;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=Je(),o=ft(),{iframeRef:i}=Vs(),[c,d]=_(""),[h,u]=_(400),[m,p]=_(!1),[f,y]=_(!1),[g,x]=_(!1),[v,b]=_(null),[w,N]=_(null),[C,S]=_([]),A=ae(()=>{var L;return!((L=e==null?void 0:e.metadata)!=null&&L.executionFlows)||!(e!=null&&e.scenarios)?[]:qs(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:E,isStarting:k,isLoading:j,showIframe:R,iframeKey:M,onIframeLoad:I}=qt({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),$=ie(async()=>{var F,L,P,O;if(!c.trim()&&C.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),N("Generating scenario with AI...");try{const z=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(F=e.metadata)==null?void 0:F.scenariosDataStructure,flowSelections:C.length>0?C:void 0})}),J=await z.json();if(!z.ok||!J.success)throw new Error(J.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",J.data);const ee=J.data;if(!ee.name||!ee.data)throw new Error("AI response missing required fields (name or data)");N("Saving new scenario..."),x(!0);const Y={name:ee.name,description:ee.description||c,metadata:{data:ee.data,interactiveExamplePath:(L=t.metadata)==null?void 0:L.interactiveExamplePath}},D=[...e.scenarios||[],Y],W=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:D})}),G=await W.json();if(!W.ok||!G.success)throw new Error(G.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",G);const Z=(O=(P=G.analysis)==null?void 0:P.scenarios)==null?void 0:O.find(re=>re.name===ee.name);if(!(Z!=null&&Z.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),N("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(E){N("Capturing screenshot...");const re=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:E,scenarioId:Z.id,projectId:e.projectId,viewportWidth:1440})}),ge=await re.json();!re.ok||!ge.success?(console.error("[CreateScenario] Capture failed:",ge),N("Scenario created! (Screenshot capture failed)")):N("Scenario created and captured!")}else N("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${Z.id}`)},1e3)}catch(z){console.error("[CreateScenario] Error:",z),b(z instanceof Error?z.message:String(z)),N(null)}finally{y(!1),x(!1)}},[c,C,e,t,s,E,o]),T=f||g,q=ie(()=>{p(!0)},[]),K=ie(F=>{if(!m)return;const L=F.clientX;L>=250&&L<=600&&u(L)},[m]),H=ie(()=>{p(!1)},[]);return X(()=>(m?(document.addEventListener("mousemove",K),document.addEventListener("mouseup",H)):(document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",H)),()=>{document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",H)}),[m,K,H]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${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})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(de,{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:l("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((U=e==null?void 0:e.scenarios)==null?void 0:U.length)||0})]})}),n(de,{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(de,{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(de,{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(de,{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"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${h}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),A.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",C.length>0&&l("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(lm,{executionFlows:A,selections:C,onChange:S,disabled:T})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:F=>d(F.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:T})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void $(),disabled:T||!c.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:T?"Creating...":"Create Scenario"}),w&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:w}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),l("div",{onMouseDown:q,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:m?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
155
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
156
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
157
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
158
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
159
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Lr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:E,isStarting:k,isLoading:j,showIframe:R,iframeKey:M,onIframeLoad:I,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const mm=Ue(function(){return n(Dr,{children:n(hm,{})})}),pm=Object.freeze(Object.defineProperty({__proto__:null,default:mm,loader:um,meta:dm},Symbol.toStringTag,{value:"Module"}));async function fm({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:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"scenarioId and url are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Re();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await De(i),d=Me(),h=await d.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",c.id).executeTakeFirst();if(!h)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${h.name}" (id: ${r}), url: ${s}`);const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=h.name.replace(/[^a-zA-Z0-9_]+/g,"_"),p=B.join(u,".codeyam","active-scenario.json");await Ce.writeFile(p,JSON.stringify({scenarioId:r,scenarioSlug:m,timestamp:new Date().toISOString()})),Ai(),console.log(`[editor-capture-scenario] Active scenario set to "${m}", cache invalidated`),await new Promise(k=>setTimeout(k,500));const f=B.join(u,".codeyam","editor-scenarios","screenshots");await Ce.mkdir(f,{recursive:!0});const y=B.join(f,`${r}.png`),g=B.dirname(new URL(import.meta.url).pathname);let x=g;for(let k=0;k<5;k++){const j=B.dirname(x);if(B.basename(j)==="webserver"||B.basename(x)==="webserver"){x=B.basename(x)==="webserver"?x:j;break}x=j}const v=[B.join(x,"scripts","journalCapture.ts"),B.join(x,"app","lib","journalCapture.ts"),B.join(u,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),B.resolve(g,"..","lib","journalCapture.ts")];let b="";for(const k of v)try{await Ce.access(k),b=k;break}catch{}b||(console.warn(`[editor-capture-scenario] journalCapture.ts not found in any of: ${v.join(", ")}`),b=v[0]),console.log(`[editor-capture-scenario] Capture script: ${b}`);const w=JSON.stringify({url:s,outputPath:y,viewportWidth:a||1280,viewportHeight:o||720});console.log(`[editor-capture-scenario] Running Playwright capture: url=${s}, output=${y}`);const N=Date.now(),C=await new Promise(k=>{const j=gt("npx",["tsx",b,w],{cwd:u,env:{...process.env}});let R="",M="";j.stdout.on("data",I=>{R+=I.toString()}),j.stderr.on("data",I=>{M+=I.toString()}),j.on("close",I=>{k(I===0?{success:!0,output:R}:{success:!1,output:R,error:M||`Process exited with code ${I}`})}),j.on("error",I=>{k({success:!1,output:"",error:I.message})})}),S=Date.now()-N;if(console.log(`[editor-capture-scenario] Capture ${C.success?"succeeded":"FAILED"} in ${S}ms`),!C.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${C.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(C.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:C.error}),{status:500,headers:{"Content-Type":"application/json"}});const A=`screenshots/${r}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:A}).where("id","=",r).execute();const E=Pi(C.output);return await _i(u,r,h.name,E),E.length>0&&console.warn(`[editor-capture-scenario] ${E.length} client-side error(s) detected:`,E),_t.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:A,clientErrors:E}),{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 gm=Object.freeze(Object.defineProperty({__proto__:null,action:fm},Symbol.toStringTag,{value:"Module"}));async function ym({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=te.join(r,".codeyam","editor-scenarios","screenshots",t),a=te.resolve(s),o=te.resolve(te.join(r,".codeyam","editor-scenarios","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{await ye.access(s);const i=await ye.readFile(s),c=te.extname(s).toLowerCase(),d=c===".png"?"image/png":c===".jpg"||c===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const xm=Object.freeze(Object.defineProperty({__proto__:null,loader:ym},Symbol.toStringTag,{value:"Module"}));async function bm({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=te.join(r,".codeyam","journal","screenshots",t),a=te.resolve(s),o=te.resolve(te.join(r,".codeyam","journal","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{await ye.access(s);const i=await ye.readFile(s),c=te.extname(s).toLowerCase(),d=c===".png"?"image/png":c===".jpg"||c===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const vm=Object.freeze(Object.defineProperty({__proto__:null,loader:bm},Symbol.toStringTag,{value:"Module"})),wm=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Cm(){const e=JSON.stringify({type:"refresh-preview"});let t=0;for(const r of wm)try{r.ws.readyState===kc.OPEN&&(r.ws.send(e),t++)}catch{}return t}async function Nm({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const a=xe()||process.cwd(),o=te.join(a,".codeyam"),i=te.join(o,"active-scenario.json");Ae.mkdirSync(o,{recursive:!0}),Ae.writeFileSync(i,JSON.stringify({scenarioSlug:r,scenarioId:s||null,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));const c=Cm();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:c}),{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 Sm=Object.freeze(Object.defineProperty({__proto__:null,action:Nm},Symbol.toStringTag,{value:"Module"}));var pe;(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={}))})(pe||(pe={}));function ji(e,t){return e?Object.values(pe.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Mi=ji(process.env.DEFAULT_SMALLER_MODEL,pe.Model.OPENAI_GPT4_1_MINI),km=ji(process.env.DEFAULT_LARGER_MODEL,pe.Model.OPENAI_GPT4_1),st={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},as={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Em={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},os={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Ct={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Am={[pe.Model.OPENAI_GPT5_1]:{id:pe.Model.OPENAI_GPT5_1,provider:st,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[pe.Model.OPENAI_GPT5]:{id:pe.Model.OPENAI_GPT5,provider:st,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[pe.Model.OPENAI_GPT5_MINI]:{id:pe.Model.OPENAI_GPT5_MINI,provider:st,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[pe.Model.OPENAI_GPT5_NANO]:{id:pe.Model.OPENAI_GPT5_NANO,provider:st,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[pe.Model.OPENAI_GPT4_1]:{id:pe.Model.OPENAI_GPT4_1,provider:st,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[pe.Model.OPENAI_GPT4_1_MINI]:{id:pe.Model.OPENAI_GPT4_1_MINI,provider:st,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[pe.Model.OPENAI_GPT4_O]:{id:pe.Model.OPENAI_GPT4_O,provider:st,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[pe.Model.OPENAI_GPT4_O_MINI]:{id:pe.Model.OPENAI_GPT4_O_MINI,provider:st,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[pe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:pe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:as,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[pe.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:pe.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:as,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[pe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:pe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:as,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[pe.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:pe.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Em,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[pe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:pe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Ct,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[pe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:pe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Ct,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[pe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:pe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Ct,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[pe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:pe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Ct,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[pe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:pe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Ct,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[pe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:pe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:os,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[pe.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:pe.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:os,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[pe.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:pe.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:os,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[pe.Model.PHIND_CODELLAMA]:{id:pe.Model.PHIND_CODELLAMA,provider:st,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[pe.Model.GOOGLE_GEMINI_PRO]:{id:pe.Model.GOOGLE_GEMINI_PRO,provider:Ct,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[pe.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:pe.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Ct,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[pe.Model.META_CODELLAMA_34B_INSTRUCT]:{id:pe.Model.META_CODELLAMA_34B_INSTRUCT,provider:Ct,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[pe.Model.OPENAI_GPT4_PREVIEW]:{id:pe.Model.OPENAI_GPT4_PREVIEW,provider:st,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Or(e){const t=Am[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Pm(e){return Or(e).maxCompletionTokens}function _m(e){return Or(e).pricing}const Qa=1e6;function jm({model:e,usage:t}){const r=_m(e);return r?t.prompt_tokens*(r.input/Qa)+t.completion_tokens*(r.output/Qa):null}function Mm({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},a=jm({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:a?Math.round(a*1e5)/1e5:void 0}}function Tm({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??Mi,i=Or(o);Pm(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Ss="/tmp/codeyam-e2e-tracking";let is,ls;function $m(){return is===void 0&&(is=process.env.CODEYAM_E2E_TRACK_DATA==="true"),is}function Im(){return ls===void 0&&(ls=!process.env.CODEYAM_LLM_FIXTURES_DIR),ls}function Rm(){Q.existsSync(Ss)||Q.mkdirSync(Ss,{recursive:!0})}function Dm(e){const t=JSON.stringify(e,null,0);return bc.createHash("md5").update(t).digest("hex")}function Lm(e,t,r){return[e].join("_")+".json"}function Ti(e,t,r,s){if(!$m())return;Rm();const a=Lm(e),o=B.join(Ss,a),i=Dm(t);if(Im()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};Q.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(Q.existsSync(o)){const c=JSON.parse(Q.readFileSync(o,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=ks(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const h=o.replace(".json","_DIFF.json");Q.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function ks(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 a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...ks(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const c of i){const d=e[c],h=t[c];c in e?c in t?s.push(...ks(d,h,`${r?r+".":""}${c}`)):s.push(`${r?r+".":""}${c}: missing in second run`):s.push(`${r?r+".":""}${c}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}Ls(Ds);const Un=new Ac({concurrency:100,timeout:1200*1e3,autoStart:!0}),Za={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Nt={};async function Es({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=Mi,attempts:i=0}){var A,E,k,j,R,M,I;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Om(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${Un.size}, running=${Un.pending}]`);const c=Date.now();let d,h=0;const u=Or(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new Ec({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=Tm(f),g=await Un.add(()=>(d=Date.now(),La(async()=>{const $=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],q=setInterval(()=>{const K=Math.floor((Date.now()-$)/1e3),H=Math.floor(K/10)%T.length;Fa(1,`${T[H]} [type=${e}, model=${o}, elapsed=${K}s]`)},1e4);try{return await p.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(q)}},{...Za,onFailedAttempt:$=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:$,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})));if(!g)throw new Error("Completion call returned no result");const x=g,v=Date.now(),b=Mm({chatRequest:f,chatCompletion:x,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=h,b.wait_ms=d-c,b.duration_ms=v-c;const w=(A=x.choices)==null?void 0:A[0];let N=null;if(w){if(!w.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");N=(E=w.message)==null?void 0:E.content}let C=N;N&&(C=N.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const S=s?C&&(((k=C.match(/\{[\s\S]*\}/))==null?void 0:k[0])??C):C;if(!S){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:S,rawCompletion:N,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Es({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(S.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:N,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(S)}catch($){if(console.log("CodeYam Error: Invalid JSON in completion",{error:$.message,model:o,completion:S.substring(0,500),rawCompletion:N==null?void 0:N.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:$.message});const T=`Your previous response contained invalid JSON with the following error:
|
|
160
|
-
|
|
161
|
-
${$.message}
|
|
162
|
-
|
|
163
|
-
Here was your previous response:
|
|
164
|
-
\`\`\`
|
|
165
|
-
${S}
|
|
166
|
-
\`\`\`
|
|
167
|
-
|
|
168
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,q=await Un.add(()=>La(async()=>{const L=Date.now(),P=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],O=setInterval(()=>{const z=Math.floor((Date.now()-L)/1e3),J=Math.floor(z/10)%P.length;Fa(1,`${P[J]} [type=${e}, model=${o}, elapsed=${z}s]`)},1e4);try{return await p.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:S},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval(O)}},{...Za,onFailedAttempt:L=>{console.log("CodeYam Error: Correction call failed",{error:L,attempts:i})}}));if(!q)throw new Error("Correction call returned no result");const K=q,H=(M=(R=(j=K.choices)==null?void 0:j[0])==null?void 0:R.message)==null?void 0:M.content;let U=H;H&&(U=H.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const F=U&&(((I=U.match(/\{[\s\S]*\}/))==null?void 0:I[0])??U);if(!F)throw new Error("Correction attempt returned empty completion");try{JSON.parse(F),console.log("CodeYam: JSON correction successful");const L=Date.now();return b.duration_ms=L-c,{finishReason:K.choices[0].finish_reason,completion:F,stats:b}}catch(L){return console.log("CodeYam Error: Corrected JSON still invalid",{error:L.message,correctedCompletion:F.substring(0,500)}),await Es({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${$.message}`)}return Ti(`completionCall_${e}`,{completion:S,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:S,stats:b}}async function Om(e,t,r){var o,i,c,d,h;const s=await import("fs"),a=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 u=s.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const m={};for(const b of u)try{const w=s.readFileSync(a.join(t,b),"utf-8"),N=JSON.parse(w);m[N.prompt_type]||(m[N.prompt_type]=[]),m[N.prompt_type].push(N)}catch(w){console.warn(`Failed to parse LLM fixture file ${b}:`,w)}for(const b of Object.keys(m))m[b].sort((w,N)=>{const C=w.created_at??0,S=N.created_at??0;return C-S});const p=m[e];if(!p||p.length===0){const b=Object.keys(m).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),w=b==null?void 0:b[1];if(w){const N={};for(const S of p)try{const E=((o=JSON.parse(S.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";N[E]||(N[E]=[]),N[E].push(S)}catch{}const C=N[w];if(C&&C.length>0){const S=`${t}::${e}::${w}`;Nt[S]===void 0&&(Nt[S]=0);const A=Nt[S];Nt[S]=(A+1)%C.length,f=C[A],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${w}' [${A+1}/${C.length}]`)}else{const S=Object.keys(N).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${w}'. Available: [${S}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;Nt[b]===void 0&&(Nt[b]=0);const w=Nt[b];Nt[b]=(w+1)%p.length,f=p[w],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${w+1}/${p.length}]`)}let g;try{g=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((h=x.match(/\{[\s\S]*\}/))==null?void 0:h[0])??x);return Ti(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function Xa(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Fm(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=Rs(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let c;const d=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?c=B.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=B.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=B.dirname(c);return await Ce.mkdir(u,{recursive:!0}),await Ce.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=Xa();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new wr().send(new Pc({TableName:Xa(),Item:jc(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new wr({});new wr({});new wr({});const zm=3,Ym=2,Gs=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+zm*String(t).length*(1+Ym)});new Os(Gs());new Os(Gs());new Os(Gs());class Bm{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 Um{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Wm{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Hm{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Jm{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Vm{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class qm{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Gm{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Km{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Qm{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class Zm{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Xm{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class ep{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class tp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class np{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class rp{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class sp{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 ap{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class op{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class ip{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function lp(){const e=new Bm;return e.register("filter",new Um,"Array"),e.register("map",new Xm,"Array"),e.register("flatMap",new ep,"Array"),e.register("join",new Zm,"Array"),e.register("find",new Jm,"Array"),e.register("findLast",new np,"Array"),e.register("at",new tp,"Array"),e.register("reduce",new Vm,"Array"),e.register("concat",new qm,"Array"),e.register("slice",new Gm,"Array"),e.register("splice",new Km,"Array"),e.register("push",new Qm,"Array"),e.register("some",new Wm,"Array"),e.register("every",new Hm,"Array"),e.register("fromEntries",new rp,"Object"),e.register("split",new sp,"String"),e.register("then",new ap,"Promise"),e.register("useState",new ip,"React"),e.register("useMemo",new op,"React"),e}lp();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 cp=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),dp=new Set(["find","findLast","at","pop","shift"]),up=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),hp=new Set([...cp,...dp,...up]),mp=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),pp=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),fp=new Set([...mp,...pp]);[...hp,...fp];class gp{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${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 gp({enabled:!1});function Ot(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function yp(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function Wn(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let xp=0;class Ks{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++xp,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 d,h,u,m;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)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 o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},c=a.stages[a.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:Ot(c.data.signatureSchema,o.signatureSchema),returnValueSchema:Ot(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of p){const y=(d=c.data.dependencySchemas)==null?void 0:d[f],g=(h=o.dependencySchemas)==null?void 0:h[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const v=`${f}::${x}`,b=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,w=(m=g==null?void 0:g[x])==null?void 0:m.returnValueSchema,N=Ot(b,w);yp(N)&&(i.diffFromPrevious.dependencySchemas[v]=N)}}}a.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 a;const t={},r=new Map;for(const[o,i]of this.traces){let c=0;for(const d of i.stages){if(!d.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(d)-1])==null?void 0:a.stage)??"start"}→${d.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),d.diffFromPrevious.signatureSchema){const m=d.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,c+=Wn(m)}if(d.diffFromPrevious.returnValueSchema){const m=d.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,c+=Wn(m)}}r.set(o,c)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);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(h=>`${h}(${this.traces.get(h).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},c=B.dirname(this.outputPath);Q.existsSync(c)||Q.mkdirSync(c,{recursive:!0});const d=Q.openSync(this.outputPath,"w");try{Q.writeSync(d,`{
|
|
169
|
-
"meta": `),Q.writeSync(d,JSON.stringify(o,null,2)),Q.writeSync(d,`,
|
|
170
|
-
"summary": `),Q.writeSync(d,JSON.stringify(i,null,2)),Q.writeSync(d,`,
|
|
171
|
-
"entities": {`);let h=!0;for(const[u,m]of this.traces)h||Q.writeSync(d,","),Q.writeSync(d,`
|
|
172
|
-
${JSON.stringify(u)}: `),Q.writeSync(d,JSON.stringify(m,null,2)),h=!1;Q.writeSync(d,`
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{Q.closeSync(d)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=Q.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new Ks({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let h=0;for(let u=1;u<d.stages.length;u++){const m=d.stages[u],f=`${((a=d.stages[u-1])==null?void 0:a.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=m.diffFromPrevious)!=null&&o.signatureSchema){const y=m.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=Wn(y)}if((i=m.diffFromPrevious)!=null&&i.returnValueSchema){const y=m.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=Wn(y)}}r.set(c,h)}const s=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges: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(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const c of s.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],h=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??h;u!==void 0&&a.push({stage:c.stage,value:u})}for(const c of s.operations)c.path===r&&a.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:a}}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 a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[h,u]of Object.entries(d))for(const[m,p]of Object.entries(u.returnValueSchema??{}))o.test(m)&&a.push({stage:i.stage,path:`${c}/${h}::${m}`,type:p,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){s=r.stages[d];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,h)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],p=u[2]==="[]";if(a.has(m))return;const f=m+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:h})};for(const[,d]of Object.entries(s.data.dependencySchemas??{}))for(const[,h]of Object.entries(d))for(const[u,m]of Object.entries(h.returnValueSchema??{}))i(u,m);const c=[];for(const[d,h]of o)new Set(h.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:h.map(m=>({...m,stage:s.stage}))});return c.sort((d,h)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(h.paths.map(p=>p.type)).size-u}),c}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(p=>p.stage===r),i=a.stages.find(p=>p.stage===s);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},h=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),m=new Set(Object.keys(h));for(const p of m)u.has(p)?d[p]!==h[p]&&c.typeChanged.push({path:p,from:d[p],to:h[p]}):c.added.push(`${p}: ${h[p]}`);for(const p of u)m.has(p)||c.removed.push(`${p}: ${d[p]}`);return c}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const c=Ot(i,s);for(const[d,h]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:h,context:{...o,changeType:"added"}});for(const[d,h]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:h,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:h,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:h,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Ot(s,a);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:h}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:h,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const c in s[i]){const d=s[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&a(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&a(d.returnValueSchema)}return}for(const i in s)for(const c in s[i]){const d=s[i][c],h={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,a,{...h,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,a,{...h,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const c in s){o[c]={};for(const d in s[c]){const h=s[c][d];o[c][d]={sig:{...h.signatureSchema||{}},rv:{...h.returnValueSchema||{}}}}}a();for(const c in s)for(const d in s[c]){const h=s[c][d],u=(i=o[c])==null?void 0:i[d],m={filePath:c,dependencyName:d};if(h.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=Ot(p,h.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,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:{...m,schemaType:"signature",changeType:"changed"}})}if(h.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=Ot(p,h.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,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:{...m,schemaType:"returnValue",changeType:"changed"}})}}}}function bp(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const eo=new Ks({enabled:bp(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{eo.isEnabled()&&eo.flush()});function $i(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 _c.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),$i(e)}return null}}function vp({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
|
|
176
|
-
User-selected Execution Flow Values:
|
|
177
|
-
The user has specifically requested these values be used in the scenario:
|
|
178
|
-
${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
179
|
-
`)}
|
|
180
|
-
|
|
181
|
-
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
182
|
-
`),`Mock Scenario Data Structure:
|
|
183
|
-
\`\`\`
|
|
184
|
-
${JSON.stringify(r,null,2)}
|
|
185
|
-
\`\`\`
|
|
186
|
-
Existing Mock Scenario Data:
|
|
187
|
-
\`\`\`
|
|
188
|
-
${JSON.stringify(t,null,2)}
|
|
189
|
-
\`\`\`
|
|
190
|
-
${a}
|
|
191
|
-
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
192
|
-
`}function wp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Nr);return`Mock Scenario Data Structure:
|
|
193
|
-
\`\`\`
|
|
194
|
-
${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
|
|
195
|
-
\`\`\`
|
|
196
|
-
|
|
197
|
-
Existing Mock Scenario Data:
|
|
198
|
-
\`\`\`
|
|
199
|
-
${JSON.stringify(s.map(i=>({name:i.name,data:vn(o.metadata.data,i.metadata.data)})),null,2)}
|
|
200
|
-
\`\`\`
|
|
201
|
-
|
|
202
|
-
Mock Scenario that should be edited: "${t}"
|
|
203
|
-
${r?`The portion of the data that should be edited:
|
|
204
|
-
\`\`\`
|
|
205
|
-
${JSON.stringify(r,null,2)}
|
|
206
|
-
\`\`\``:""}
|
|
207
|
-
|
|
208
|
-
How this data should be changed: "${e}"
|
|
209
|
-
`}async function Cp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const c=t?wp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):vp({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),d=await Es({type:"guessScenarioDataFromDescription",systemMessage:t?Sp(r):Np,prompt:c,model:i??km});await Fm({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...d.stats});const{completion:h}=d;return h?$i(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Np=`
|
|
210
|
-
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.
|
|
211
|
-
|
|
212
|
-
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.
|
|
213
|
-
|
|
214
|
-
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.
|
|
215
|
-
|
|
216
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
217
|
-
\`\`\`
|
|
218
|
-
export type ScenarioData = {
|
|
219
|
-
name: string;
|
|
220
|
-
description: string;
|
|
221
|
-
data: {
|
|
222
|
-
mockData: { [key: string]: unknown };
|
|
223
|
-
argumentsData: { [key: string]: unknown };
|
|
224
|
-
};
|
|
225
|
-
};
|
|
226
|
-
|
|
227
|
-
\`\`\`
|
|
228
|
-
`,Sp=e=>`
|
|
229
|
-
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.
|
|
230
|
-
|
|
231
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
232
|
-
${e?`
|
|
233
|
-
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.`:""}
|
|
234
|
-
|
|
235
|
-
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.
|
|
236
|
-
|
|
237
|
-
You must respond with valid JSON following this type definition:
|
|
238
|
-
\`\`\`
|
|
239
|
-
{
|
|
240
|
-
data: {
|
|
241
|
-
mockData: { [key: string]: unknown };
|
|
242
|
-
argumentsData: { [key: string]: unknown };
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
\`\`\`
|
|
246
|
-
`;async function kp({request:e}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return V({error:"Missing required field: description or flowSelections"},{status:400});const d=await Cp({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}),h=(d==null?void 0:d.data)||d;return V({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),V({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ep=Object.freeze(Object.defineProperty({__proto__:null,action:kp},Symbol.toStringTag,{value:"Module"}));async function Ap({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:a,description:o}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=B.join(i,".codeyam","journal"),d=B.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let h={entries:[]};try{const p=await Ce.readFile(d,"utf8");h=JSON.parse(p)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const u=h.entries.findIndex(p=>p.time===r);if(u===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const m=h.entries[u];if(s!==void 0&&(m.commitSha=s),a!==void 0&&(m.commitMessage=a),o!==void 0&&(m.description=o),h.entries[u]=m,await Ce.writeFile(d,JSON.stringify(h,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const p=m.date,f=B.join(c,`${p}.md`);let y="";try{y=await Ce.readFile(f,"utf8")}catch{}if(y){const g=`
|
|
247
|
-
**Commit:** \`${s}\` — ${a||"no message"}
|
|
248
|
-
`,x=`### ${m.title}`,v=y.lastIndexOf(x);if(v!==-1){const b=y.indexOf(`
|
|
249
|
-
---
|
|
250
|
-
`,v+1),w=b!==-1?b:y.length;y=y.slice(0,w)+g+y.slice(w),await Ce.writeFile(f,y,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${f}`)}}}catch(p){console.warn("[editor-journal-update] Failed to update markdown:",p)}return _t.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 Pp=Object.freeze(Object.defineProperty({__proto__:null,action:Ap},Symbol.toStringTag,{value:"Module"}));async function _p({request:e}){try{const t=process.env.CODEYAM_ROOT_PATH||process.cwd(),r=await nm(t);let s=0;const a={};for(const[o,i]of Object.entries(r))i.errors.length>0&&(a[o]=i,s+=i.errors.length);return new Response(JSON.stringify({hasErrors:s>0,totalErrors:s,scenarios:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-client-errors] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const jp=Object.freeze(Object.defineProperty({__proto__:null,loader:_p},Symbol.toStringTag,{value:"Module"}));async function Mp({request:e}){try{const r=(await Vt()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const c=i.analyses[0],d=c.scenarios||[],h=!((y=c.status)!=null&&y.finishedAt),u=i.entityType||"visual",p=u==="library"||u==="functionCall"?d.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):d.some(g=>{var x,v,b,w;return((v=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:v[0])&&!((b=g.metadata)!=null&&b.noScreenshotSaved)&&!((w=g.metadata)!=null&&w.sameAsDefault)}),f=d.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:p,isAnalyzing:h,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{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 Tp=Object.freeze(Object.defineProperty({__proto__:null,loader:Mp},Symbol.toStringTag,{value:"Module"}));async function $p(e){console.log(`[editor-journal-entry] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Re();if(!t)return console.warn("[editor-journal-entry] No project slug found — cannot look up scenarios"),[];const{project:r}=await De(t),a=await Me().selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",r.id).where("name","in",e).execute();console.log(`[editor-journal-entry] DB query returned ${a.length} matching scenarios:`,a.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const o=a.filter(c=>c.screenshot_path).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id})),i=a.filter(c=>!c.screenshot_path);return i.length>0&&console.warn(`[editor-journal-entry] ${i.length} scenarios have no screenshot_path:`,i.map(c=>c.name)),console.log(`[editor-journal-entry] Found ${o.length} scenarios with screenshots`),o}catch(t){return console.error("[editor-journal-entry] Failed to look up scenario screenshots:",t),[]}}async function Ip(){console.log("[editor-journal-entry] Looking up all session scenario screenshots");try{const e=await Re();if(!e)return console.warn("[editor-journal-entry] No project slug found — cannot look up session scenarios"),[];const{project:t}=await De(e),r=Me(),s=xe()||process.cwd(),a=B.join(s,".codeyam","editor-step.json");let o=null;try{const h=Q.readFileSync(a,"utf8");o=JSON.parse(h).featureStartedAt||null}catch{return console.warn("[editor-journal-entry] No editor-step.json found — cannot determine session start"),[]}if(!o)return console.warn("[editor-journal-entry] No featureStartedAt in editor-step.json"),[];const i=o.replace("T"," ").replace(/\.\d{3}Z$/,""),c=await r.selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",t.id).where("created_at",">=",i).orderBy("created_at","asc").execute();console.log(`[editor-journal-entry] Session query returned ${c.length} scenarios since ${o}`);const d=c.filter(h=>h.screenshot_path).map(h=>({name:h.name,screenshotPath:h.screenshot_path,scenarioId:h.id}));return console.log(`[editor-journal-entry] Found ${d.length} session scenarios with screenshots`),d}catch(e){return console.error("[editor-journal-entry] Failed to look up session scenario screenshots:",e),[]}}async function Rp({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:a,scenarios:o,includeSessionScenarios:i,screenshot:c,commitSha:d,commitMessage:h}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${c||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=B.join(u,".codeyam","journal"),p=B.join(m,"screenshots");await Ce.mkdir(p,{recursive:!0});const f=new Date,y=f.toISOString().split("T")[0],g=f.toISOString(),x=[];let v=o||[];const b=i?await Ip():o&&o.length>0?await $p(o):[];i&&b.length>0&&(v=b.map(k=>k.name));for(const k of b){const j=B.join(u,".codeyam","editor-scenarios",k.screenshotPath),R=k.name.replace(/[^a-zA-Z0-9_\-]/g,"_"),I=`${f.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${R}.png`,$=B.join(p,I);console.log(`[editor-journal-entry] Copying scenario screenshot: "${k.name}" from ${j} → ${$}`);try{await Ce.access(j),await Ce.copyFile(j,$),x.push({name:k.name,path:`screenshots/${I}`}),console.log(`[editor-journal-entry] Successfully copied screenshot for "${k.name}"`)}catch(T){console.warn(`[editor-journal-entry] Scenario screenshot not found: ${j}`,T instanceof Error?T.message:T)}}console.log(`[editor-journal-entry] Scenario screenshot summary: ${x.length} scenarios have screenshots embedded`);const w=B.join(m,`${y}.md`);let N="";try{N=await Ce.readFile(w,"utf8")}catch{N=`# Development Journal — ${y}
|
|
251
|
-
`}const C=["","---","",`### ${r}`,`**Time:** ${g}`,`**Type:** ${s}`];if(v.length>0&&C.push(`**Scenarios:** ${v.join(", ")}`),C.push(""),C.push(a),c&&(C.push(""),C.push(``)),x.length>0){C.push(""),C.push("**Scenario Screenshots:**");for(const k of x)C.push(""),C.push(``)}d&&h&&(C.push(""),C.push(`**Commit:** \`${d}\` — ${h}`)),C.push(""),await Ce.writeFile(w,N+C.join(`
|
|
252
|
-
`),"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${w}`);const S=B.join(m,"index.json");let A={entries:[]};try{const k=await Ce.readFile(S,"utf8");A=JSON.parse(k)}catch{}const E={date:y,time:g,title:r,type:s,description:a,scenarios:v,screenshot:c||null,scenarioScreenshots:x,commitSha:d||null,commitMessage:h||null};return A.entries.push(E),await Ce.writeFile(S,JSON.stringify(A,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${A.entries.length} entries)`),_t.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${x.length}`),new Response(JSON.stringify({success:!0,entry:E,scenarioScreenshotsFound:x.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 Dp=Object.freeze(Object.defineProperty({__proto__:null,action:Rp},Symbol.toStringTag,{value:"Module"}));function Lp({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=xe()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const d=B.join(r,".codeyam","active-scenario.json");if(!Q.existsSync(d))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(Q.readFileSync(d,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=B.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!Q.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const c=Q.readFileSync(i,"utf-8");return new Response(c,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const Op=Object.freeze(Object.defineProperty({__proto__:null,loader:Lp},Symbol.toStringTag,{value:"Module"}));async function Fp(e,t){const r=xe();if(!r)return{entityCalls:[],analysisCalls:[]};const s=B.join(r,".codeyam","llm-calls");try{await Ce.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const c=(await Ce.readdir(s)).filter(v=>v.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],m=[];for(const v of c)v.startsWith(d)||h&&v.startsWith(h)?u.push(v):m.push(v);const p=u.map(async v=>{try{const b=B.join(s,v),w=await Ce.readFile(b,"utf-8");return JSON.parse(w)}catch{return null}}),f=m.map(async v=>{try{const b=B.join(s,v),w=await Ce.readFile(b,"utf-8"),N=JSON.parse(w);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?a.push(v):t&&v.object_id===t&&o.push(v);a.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function zp({params:e,request:t}){const{entitySha:r}=e;if(!r)return V({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Fp(r,a);return V(o)}const Yp=Object.freeze(Object.defineProperty({__proto__:null,loader:zp},Symbol.toStringTag,{value:"Module"}));function Bp(e){try{const t=B.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 Up(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const c of s)for(const d of c.assertionResults||[]){const h=d.ancestorTitles||[],u=d.title||d.fullName||"unknown",m=h.length>0?`${h.join(" > ")} > ${u}`:u;a.push({title:u,fullName:m,status:d.status==="passed"?"passed":d.status==="failed"?"failed":"skipped",duration:d.duration,failureMessages:(i=d.failureMessages)!=null&&i.length?d.failureMessages:void 0})}const o=a.some(c=>c.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function Wp(e,t){const r=Bp(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=B.isAbsolute(t)?t:B.join(e,t);if(!Q.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=B.join(Do.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var m;let i,c;r==="vitest"?(c="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(c="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPattern",t]);const d=gt(c,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let h="";(m=d.stderr)==null||m.on("data",p=>{h+=p.toString()});const u=setTimeout(()=>{d.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);d.on("close",()=>{clearTimeout(u);try{const p=Q.readFileSync(a,"utf8");Q.unlinkSync(a),o(Up(t,p))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:h.trim().slice(0,500)||"Test runner failed to produce output"})}}),d.on("error",p=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${p.message}`})})})}async function Hp({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=xe()||process.cwd();try{const a=await Wp(s,r);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const Jp=Object.freeze(Object.defineProperty({__proto__:null,loader:Hp},Symbol.toStringTag,{value:"Module"}));function Vp(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=je("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return qp(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function qp(e){const t=e.trim().split(`
|
|
253
|
-
`).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),c,d=!1,h;if(a==="A"||o==="A")c="added",d=a==="A";else if(a==="M"||o==="M")c="modified",d=a==="M";else if(a==="D"||o==="D")c="deleted",d=a==="D";else if(a==="R"||o==="R"){c="renamed",d=a==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=te.join(u,i);try{const p=(y,g)=>{const x=Ae.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const w=te.join(y,b.name),N=te.relative(u,w);b.isDirectory()?v.push(...p(w,g)):b.isFile()&&v.push(N)}return v},f=p(m,u);for(const y of f)r.push({path:y,status:c,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:c,staged:d,...h&&{oldPath:h}})}return r}function Gp(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je("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 Kp(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=je('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 je("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return je("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 Qp(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
254
|
-
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Ii(){const e=xe();return e?Vp(e):[]}function Zp(){const e=xe();return e?Gp(e):null}function Xp(){const e=xe();return e?Kp(e):"main"}function ef(){const e=xe();return e?Qp(e):[]}function Ri(e,t){const r=xe();return r?tf(e,t,r):[]}function tf(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
255
|
-
`).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let h=c[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=c[1],h=c[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function nf(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=je(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=Ae.readFileSync(te.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,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 rf(e){const t=xe();return t?nf(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function sf(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=je(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=je(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Kn(e,t,r){const s=xe();return s?sf(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function to(e,t){var r,s;try{return((s=(r=je(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function af(e,t,r,s){const a=xr.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function Di(){const e=xe();if(!e)throw new Error("No project root found");const t=te.join(e,".codeyam","cache","branch-entity-diff");return Ae.existsSync(t)||Ae.mkdirSync(t,{recursive:!0}),t}function of(e){try{const t=Di(),r=te.join(t,`${e}.json`);if(!Ae.existsSync(r))return null;const s=Ae.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function lf(e,t){try{const r=Di(),s=te.join(r,`${e}.json`);Ae.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function cf(e,t,r){const s=or(t,e),a=or(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),c=[],d=[],h=[];for(const[u,m]of i){const p=o.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):c.push(m)}for(const[u,m]of o)i.has(u)||h.push(m);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:h}}function df(e,t){const r=xe();if(!r)throw new Error("No project root found");const s=to(e,r),a=to(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=af(e,t,s,a),i=of(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=Ri(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=Kn(u.path,e,t),p=or(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=Kn(u.path,e,t),p=or(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=Kn(u.path,e,t),p=cf(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return lf(o,h),h}function uf({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return V({error:"Missing required parameters: base and compare"},{status:400});const a=df(r,s);return V(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),V({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const hf=Object.freeze(Object.defineProperty({__proto__:null,loader:uf},Symbol.toStringTag,{value:"Module"}));async function mf({request:e}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return V({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=xe();if(!i)return V({error:"Project root not found"},{status:500});const c=B.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),h=await new Promise(p=>{const f=B.join(i,".codeyam","db.sqlite3"),y=gt("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",v=>{const b=v.toString();g+=b;const w=b.trim().split(`
|
|
256
|
-
`);for(const N of w)N.includes("[Capture]")&&console.log(N)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{p(v===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${v}`})}),y.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),p({success:!1,output:"",error:v.message})})});if(!h.success)return V({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return V({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return V(m)}catch(t){return console.error("[Capture] Error:",t),V({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const pf=Object.freeze(Object.defineProperty({__proto__:null,action:mf},Symbol.toStringTag,{value:"Module"}));async function ff(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await We();const s=await bt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=Me(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} 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 an(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=xe();if(!d)throw new Error("Project root not found");const h=B.join(d,".codeyam","config.json"),u=JSON.parse(Q.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function gf(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await We();const s=await bt({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 a=(u=s.scenarios)==null?void 0:u.find(m=>m.id===t);if(!a)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: ${a.name}`),await an(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===a.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=xe();if(!o)throw new Error("Project root not found");const i=B.join(o,".codeyam","config.json"),c=JSON.parse(Q.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function yf({request:e,context:t}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await vt()),!r)return V({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return V({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await gf(a,o,r);return console.log("[API] Scenario recapture queued",i),V({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),V({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const xf=Object.freeze(Object.defineProperty({__proto__:null,action:yf},Symbol.toStringTag,{value:"Module"}));async function As(e){try{return await ye.stat(e),!0}catch{return!1}}async function Li(){try{const e=xe();if(!e)return null;const t=te.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function bf(){return`/private/tmp/claude-501/-${(xe()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Qn="/tmp/claude-rule-markers",vf=/<system-reminder>[\s\S]*?<\/system-reminder>/g,no=2e3;function wf(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 Cf=["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 Nf(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 a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function Sf(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 a=s.indexOf(`
|
|
257
|
-
###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function kf(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of Cf)if(r.includes(s))return!0}return!1}function Ef(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function Af(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function Pf(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,h=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:h,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,p=String(m.tool_use_id||"");let f=m.content;const y=!!m.is_error;typeof f=="string"&&(f=f.replace(vf,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:h})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const p=String(m.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:h})}else if(m.type==="tool_use"){const p=String(m.id||""),f=String(m.name||"unknown"),y=m.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:y,timestamp:h})}}}return t}function _f(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 Kt=20;async function ro(e){const r=(await ye.readFile(e.filePath,"utf-8")).split(`
|
|
258
|
-
`),s=Pf(r);if(s.length===0)return null;const a=s.find(w=>w.type==="user_prompt"),o=e.stem,i=Ef(r);let c=(a==null?void 0:a.slug)||"",d=(a==null?void 0:a.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let h;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?c=c||"rule-reflection/stale":e.stem.endsWith("-conversation")?c=c||"rule-reflection/conversation":e.stem.endsWith("-interruption")?c=c||"rule-reflection/interruption":c=c||"rule-reflection";const w=e.filePath.replace(/\.log$/,".context");if(await As(w))try{h=await ye.readFile(w,"utf-8")}catch{}}const u=s.filter(w=>w.type==="tool_call").length,m=s.filter(w=>w.type==="assistant_text").length,p=s.filter(w=>w.type==="tool_result"&&w.is_error&&w.content!=="Sibling tool call errored"),f=p.length,y=p.map(w=>{const N=w.content||"Unknown error";return N.length>150?N.slice(0,150)+"...":N});for(const w of s)w.type==="tool_call"&&w.name&&w.input&&(w.summary=wf(w.name,w.input));for(const w of s)w.type==="tool_result"&&w.content&&w.content.length>no&&(w.truncated=!0,w.fullLength=w.content.length,w.content=w.content.slice(0,no));const g=Nf(s),x=kf(s),v=Sf(h),b=Af(r);return{id:o,slug:c,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:m,errors:f,errorMessages:y},entries:s,context:h,conversationSnippet:v,ruleChanges:g,hasConfusion:x,sessionResult:b}}async function jf(){const e=bf(),t=Qn,r=[];if(await As(e)){const i=await ye.readdir(e);for(const c of i)if(c.endsWith(".output")){const d=te.join(e,c),h=await ye.stat(d);r.push({filePath:d,stem:c.replace(".output",""),mtime:h.mtimeMs})}}const s=new Set,a=await Li(),o=[];a&&o.push(te.join(t,a)),o.push(t);for(const i of o){if(!await As(i))continue;const c=await ye.readdir(i);for(const d of c){if(!d.endsWith(".log")||s.has(d))continue;s.add(d);const h=te.join(i,d),u=await ye.stat(h);r.push({filePath:h,stem:d.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,c)=>c.mtime-i.mtime),r}async function Mf({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await jf();if(!s){const u=o.length,m=(a-1)*Kt,p=o.slice(m,m+Kt),f=[];for(const y of p){const g=await ro(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:Kt})}const i=[];for(const u of o){const m=await ro(u);if(!m)continue;(m.id.toLowerCase().includes(s)||m.slug.toLowerCase().includes(s)||m.entries.some(f=>_f(f,s)))&&i.push(m)}const c=i.length,d=(a-1)*Kt,h=i.slice(d,d+Kt);return Response.json({agents:h,total:c,page:a,pageSize:Kt})}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 Tf=Object.freeze(Object.defineProperty({__proto__:null,loader:Mf},Symbol.toStringTag,{value:"Module"})),Oi="__codeyam_editor_dev_server__",so=30;function Qs(){return globalThis[Oi]??null}function Fi(e){globalThis[Oi]=e}function cs(e,t){const r=[te.join(e,".next","dev","lock"),te.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{Ae.existsSync(s)&&(Ae.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=je(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(je(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function $f({request:e}){const t=Qs();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Si(),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 If({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"?Ps():r==="stop"?ao():r==="restart"?(ao(),await new Promise(s=>setTimeout(s,1e3)),Ps()):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 Ps(e=!1){var m,p,f,y;const t=Qs();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=xe()||process.cwd(),s=te.join(r,"package.json");if(!Ae.existsSync(s))return new Response(JSON.stringify({error:"No package.json found. Scaffold a project first."}),{status:400,headers:{"Content-Type":"application/json"}});let a="npm",o=["run","dev"];try{const g=JSON.parse(Ae.readFileSync(s,"utf8"));if(Ae.existsSync(te.join(r,"pnpm-lock.yaml"))?a="pnpm":Ae.existsSync(te.join(r,"yarn.lock"))?a="yarn":Ae.existsSync(te.join(r,"bun.lockb"))&&(a="bun"),!((m=g.scripts)!=null&&m.dev))if((p=g.scripts)!=null&&p.start)o=["run","start"];else return new Response(JSON.stringify({error:'No "dev" or "start" script found in package.json.'}),{status:400,headers:{"Content-Type":"application/json"}})}catch{}cs(r,3e3),cs(r,3001),cs(r,5173),console.log(`[editor-dev-server] Starting: ${a} ${o.join(" ")} in ${r}`);const i=gt(a,o,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"},detached:!0});i.unref();const c=e?((t==null?void 0:t.retryCount)??0)+1:0,d={process:i,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:i.pid||0,startedAt:Date.now(),retryCount:c};Fi(d);const h=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/],u=(g,x)=>{const v=g.toString();if(x){const b=v.split(`
|
|
259
|
-
`).filter(w=>w.trim());d.stderrBuffer.push(...b),d.stderrBuffer.length>so&&(d.stderrBuffer=d.stderrBuffer.slice(-so))}if(d.status==="starting")for(const b of h){const w=v.match(b);if(w){const N=w[1]||w[0];d.url=N.replace(/\x1b\[[0-9;]*m/g,"").trim(),d.status="running",console.log(`[editor-dev-server] URL detected: ${d.url}`);const C=parseInt(process.env.CODEYAM_PORT||"3111",10);ki({port:C+1,targetUrl:d.url});break}}};return(f=i.stdout)==null||f.on("data",g=>u(g,!1)),(y=i.stderr)==null||y.on("data",g=>u(g,!0)),i.on("exit",g=>{console.log(`[editor-dev-server] Process exited with code ${g}`);const x=Date.now()-d.startedAt,v=x<1e4;g!==0&&g!==null&&v&&d.retryCount===0?(console.log(`[editor-dev-server] Quick failure (${x}ms), auto-retrying...`),d.status="stopped",Ps(!0)):g!==0&&g!==null?(d.status="error",d.errorMessage=d.stderrBuffer.length>0?d.stderrBuffer.join(`
|
|
260
|
-
`):`Dev server exited with code ${g}`,console.error(`[editor-dev-server] Server failed: ${d.errorMessage}`)):d.status="stopped"}),i.on("error",g=>{console.error("[editor-dev-server] Process error:",g),d.status="error",d.errorMessage=g.message}),new Response(JSON.stringify({status:"starting",pid:i.pid,message:`Starting ${a} ${o.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function ao(){const e=Qs();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Ei();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",Fi(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const Rf=Object.freeze(Object.defineProperty({__proto__:null,action:If,loader:$f},Symbol.toStringTag,{value:"Module"}));async function Df({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=_r(r);try{return await bn(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Lf({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=_r(t);try{if(!kt(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 ys(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 a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Of=Object.freeze(Object.defineProperty({__proto__:null,action:Df,loader:Lf},Symbol.toStringTag,{value:"Module"}));async function Ff(){const e=await Re();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await De(e),r=Me(),s=process.env.CODEYAM_PORT||"3111",a=xe()||process.cwd(),o=B.join(a,".codeyam","editor-step.json");let i=null;try{const u=Q.readFileSync(o,"utf8");i=JSON.parse(u).featureStartedAt||null}catch{}let c=r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path"]).where("project_id","=",t.id);if(i){const u=i.replace("T"," ").replace(/\.\d{3}Z$/,"");c=c.where("created_at",">=",u)}const h=(await c.orderBy("created_at","asc").execute()).map(u=>({id:u.id,name:u.name,componentName:u.component_name||null,link:`http://localhost:${s}/editor?scenario=${u.id}&ref=link`}));return Response.json({scenarios:h})}const zf=Object.freeze(Object.defineProperty({__proto__:null,loader:Ff},Symbol.toStringTag,{value:"Module"}));async function Yf(e,t){var o,i,c,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await We();const r=await bt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(m=>m.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 a={returnValue:{status:"success",data:((d=(c=(i=s.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=s.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function Bf({request:e}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return V({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await Yf(r,s);return console.log("[API] Function execution completed successfully"),V({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),V({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Uf=Object.freeze(Object.defineProperty({__proto__:null,action:Bf},Symbol.toStringTag,{value:"Module"}));function Wf({request:e}){return V({status:"ok"})}async function Hf({request:e,context:t}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await vt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),V({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return V({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return V({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await Re();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return V({error:"Project not initialized"},{status:500});if(a==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return V({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return V({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),V({error:"Failed to control interactive mode",details:a},{status:500})}}const Jf=Object.freeze(Object.defineProperty({__proto__:null,action:Hf,loader:Wf},Symbol.toStringTag,{value:"Module"}));async function Vf({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 a=xe();if(a)for(const o of s){const i=te.join(a,".codeyam","captures","screenshots",o);try{await ye.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await Pd({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const qf=Object.freeze(Object.defineProperty({__proto__:null,action:Vf},Symbol.toStringTag,{value:"Module"}));class Gf extends vr{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 _s="__codeyam_dev_mode_event_emitter__";if(!globalThis[_s]){const e=new Gf;e.setMaxListeners(20),globalThis[_s]=e}const oo=globalThis[_s];function Kf({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
261
|
-
|
|
262
|
-
`));let a=!1;const o=()=>{if(!a){a=!0,oo.off("event",i),clearInterval(c);try{r.close()}catch{}}},i=d=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(d)}
|
|
263
|
-
|
|
264
|
-
`))}catch{o()}};oo.on("event",i);const c=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
265
|
-
|
|
266
|
-
`))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Qf=Object.freeze(Object.defineProperty({__proto__:null,loader:Kf},Symbol.toStringTag,{value:"Module"})),En="/tmp/codeyam",js=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",zi=500,Zf=zi*1024*1024;function zt(e,t){try{return je(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Zn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Yi(e){return zt("config user.email",e)}function Xf(e){const t=B.join(e,".codeyam","debug-report.md");if(!Q.existsSync(t))return null;try{return Q.readFileSync(t,"utf8")}catch{return null}}function eg(e,t=20){const r=B.join(En,"local-dev",e,"codeyam","log.txt");if(!Q.existsSync(r))return[];try{return Q.readFileSync(r,"utf8").split(`
|
|
267
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function tg(e){try{const t=await fetch(`${js}/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 ng(e,t){try{je(`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 rg(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),h=B.join(En,`delta-staging-${d}`),u=B.join(h,"delta");Q.mkdirSync(u,{recursive:!0});try{const m=zt("diff --binary HEAD",t)||"";Q.writeFileSync(B.join(u,"tracked.patch"),m?m+`
|
|
268
|
-
`:"");const p=zt("ls-files --others --exclude-standard",t);if(p){const x=B.join(u,"untracked");Q.mkdirSync(x,{recursive:!0});for(const v of p.split(`
|
|
269
|
-
`).filter(Boolean)){const b=B.join(t,v),w=B.join(x,v);if(Q.existsSync(b)){const N=B.dirname(w);Q.mkdirSync(N,{recursive:!0}),Q.statSync(b).isFile()&&Q.copyFileSync(b,w)}}}const f=B.join(t,".codeyam");if(Q.existsSync(f)){const x=B.join(u,"codeyam");Q.cpSync(f,x,{recursive:!0})}Q.writeFileSync(B.join(u,"meta.json"),JSON.stringify(a,null,2));const y=B.join(En,"local-dev",r,"codeyam","log.txt");Q.existsSync(y)?Q.copyFileSync(y,B.join(u,"codeyam-log.txt")):Q.writeFileSync(B.join(u,"codeyam-log.txt"),`# Log file not found
|
|
270
|
-
`);const g=B.join(t,".codeyam","debug-report.md");Q.existsSync(g)&&(Q.copyFileSync(g,B.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(Q.writeFileSync(B.join(u,"screenshot.jpg"),o),c(`Screenshot included (${Zn(o.length)})`));try{je(`tar -czf "${s}" -C "${h}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{Q.rmSync(h,{recursive:!0,force:!0})}}async function sg(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=zt("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=zt("rev-parse --abbrev-ref HEAD",t)||"unknown",h=zt("status --porcelain",t),u=zt("remote get-url origin",t),m=h!==null&&h.length>0,p=pi(r),f=Xf(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:c,branch:d,isDirty:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=B.join(En,`base-${c}-${x}.tar.gz`),b=B.join(En,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const w=await tg(c);let N=null;w?i("Server already has base, skipping..."):(i("Generating base archive..."),ng(t,v),N=Q.statSync(v).size,i(`Base archive: ${Zn(N)}`)),i("Generating delta archive..."),rg({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:a,onProgress:o});const S=Q.statSync(b).size;i(`Delta archive: ${Zn(S)}`);const A=(N||0)+S;if(A>Zf)throw Q.existsSync(v)&&Q.unlinkSync(v),Q.unlinkSync(b),new Error(`Bundle too large: ${Zn(A)} (max: ${zi} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:w?null:v,deltaPath:b,metadata:g,baseSha:c,baseSize:N,deltaSize:S}}async function ag(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),h=Q.statSync(r),u=t?Q.statSync(t):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${js}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!p.ok){const w=await p.json();throw new Error(w.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await p.json(),x=[];if(t&&g){d("Uploading base...");const w=Q.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(N=>{if(!N.ok)throw new Error(`Base upload failed: ${N.status}`)}))}d("Uploading delta...");const v=Q.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(w=>{if(!w.ok)throw new Error(`Delta upload failed: ${w.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${js}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const w=await b.json();throw new Error(w.error||`Confirm failed: ${b.status}`)}return t&&Q.existsSync(t)&&Q.unlinkSync(t),Q.unlinkSync(r),{bundleId:f}}async function og({request:e}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),c=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("entityName"),m=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(p?g=`Issue on ${u} scenario "${p}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const A=await y.arrayBuffer();x=Buffer.from(A),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=xe();if(!v)return V({error:"Project root not found"},{status:500});const b=await Re();if(!b)return V({error:"Project slug not found"},{status:500});const w={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:eg(b,20),entityName:u||void 0,entityType:m||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${w.source}, issue: ${w.issueType}`);const N=await sg({projectRoot:v,projectSlug:b,feedback:w,screenshot:x,onProgress:A=>{console.log(`[Bundle] ${A}`)}}),C=(N.baseSize||0)+N.deltaSize;console.log(`[Bundle] Archives created: delta=${N.deltaSize} bytes${N.basePath?`, base=${N.baseSize} bytes`:" (base reused)"}`);const S=await ag({basePath:N.basePath,deltaPath:N.deltaPath,projectSlug:b,metadata:N.metadata,baseSha:N.baseSha,deltaSize:N.deltaSize,onProgress:A=>{console.log(`[Bundle] ${A}`)}});return console.log(`[Bundle] Upload complete: ${S.bundleId}`),V({success:!0,reportId:S.bundleId,size:C})}catch(t){return console.error("[Bundle] Error:",t),V({error:t.message||"Failed to generate bundle"},{status:500})}}function ig(){const e=xe(),t=e?Yi(e):null;return V({defaultEmail:t})}const lg=Object.freeze(Object.defineProperty({__proto__:null,action:og,loader:ig},Symbol.toStringTag,{value:"Module"}));async function cg({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=B.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const c=await Ce.readFile(a,"utf8");o=JSON.parse(c)}catch{}let i=o.entries;return r&&(i=i.filter(c=>c.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 dg=Object.freeze(Object.defineProperty({__proto__:null,loader:cg},Symbol.toStringTag,{value:"Module"}));function Bi(e){if(!Q.existsSync(e))return qe.Unknown;try{const t=JSON.parse(Q.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?qe.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?qe.Remix:r["react-scripts"]?qe.CRA:qe.Unknown}catch{return qe.Unknown}}function ug(e,t){let r=e;const s=B.resolve(t);for(;;){const a=B.resolve(r);if(Q.existsSync(B.join(a,"pnpm-lock.yaml")))return"pnpm";if(Q.existsSync(B.join(a,"yarn.lock")))return"yarn";if(Q.existsSync(B.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=B.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function hg(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function mg(e){const t=B.join(e,"package.json");if(!Q.existsSync(t))return{isWebApp:!1};if(Bi(t)===qe.Unknown)return{isWebApp:!1};try{const a=JSON.parse(Q.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel"],c=Object.keys(a).filter(d=>["dev","start","serve","build"].some(h=>d.includes(h))).filter(d=>o.some(h=>a[d].includes(h)));if(c.length===0)return{isWebApp:!1};for(const d of c){const h=a[d],u=hg(h);if(u){const m=B.join(e,u);if(Q.existsSync(m)&&Q.statSync(m).isDirectory())return{isWebApp:!0,actualPath:m}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Ui(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=mg(t);if(o.isWebApp){const c=o.actualPath||t,d=B.relative(e,c);return a.push(d||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const c=Q.readdirSync(t,{withFileTypes:!0});for(const d of c)if(d.isDirectory()&&!i.includes(d.name)){const h=B.join(t,d.name);a.push(...Ui(e,h,r+1,s))}}catch{}return a}function pg(e){const t=Ui(e);return t.length===0?[]:t.map(s=>{const a=B.join(e,s),o=B.join(a,"package.json"),i=Bi(o),c=ug(a,e);let d;if(i===qe.Remix||i===qe.Next){const m=B.join(a,"app");Q.existsSync(m)&&Q.statSync(m).isDirectory()&&(d="app")}const h=fg(s,e),u=h?{command:"sh",args:["-c",`${c} run ${h} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:c,appDirectory:d,startCommand:u}})}function fg(e,t){const r=B.join(t,e),s=B.join(r,"package.json");if(!Q.existsSync(s))return null;try{const o=JSON.parse(Q.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const c of i)if(o[c])return c;return null}catch{return null}}async function gg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=xe()||process.cwd(),r=te.join(t,".codeyam","config.json");let s=[];try{s=pg(t)}catch{}if(Ae.existsSync(r)){const i=JSON.parse(Ae.readFileSync(r,"utf8"));i.webapps=s,Ae.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Re();if(a)try{await nn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",d=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(d.status==="stopped"||d.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,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 yg=Object.freeze(Object.defineProperty({__proto__:null,action:gg},Symbol.toStringTag,{value:"Module"}));function Bt(){const e=process.memoryUsage(),t=Mc.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(xs.totalmem()/1024/1024),freeMemory:Math.round(xs.freemem()/1024/1024)}}}function xg(){const e=Bt();console.log(`
|
|
271
|
-
[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 bg(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Bt();global.gc();const t=Bt(),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 vg(){const e=Bt(),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 wg({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=bg(),a=Bt();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=xg();return Response.json({success:!0,stats:s})}case"leaks":{const s=vg(),a=Bt();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Bt();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 Cg=Object.freeze(Object.defineProperty({__proto__:null,loader:wg},Symbol.toStringTag,{value:"Module"})),Hn=Ls(Ds);async function Ng({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(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=Sg(o),c=i?await kg(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:a})}function Sg(e){try{return process.kill(e,0),!0}catch{return!1}}async function kg(e){if(process.platform==="win32")try{const{stdout:r}=await Hn(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await Hn(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await Hn(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await Hn(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const Eg=Object.freeze(Object.defineProperty({__proto__:null,loader:Ng},Symbol.toStringTag,{value:"Module"})),Ag=br(import.meta.url),Pg=B.dirname(Ag);function _g({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=gi(),r=xe()||(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,a=B.join(Pg,"..","..","..","..","webserver","bootstrap.js"),o=B.join(r,".codeyam","logs");Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0});const i=Q.openSync(B.join(o,"background-server.log"),"a"),c=Q.openSync(B.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();Q.appendFileSync(B.join(o,"background-server.log"),`
|
|
272
|
-
[${d}] Server restart requested via dashboard
|
|
273
|
-
`),Ru();const h=gt("node",[a],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const jg=Object.freeze(Object.defineProperty({__proto__:null,action:_g},Symbol.toStringTag,{value:"Module"}));async function Mg({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((c,d)=>{var m,p,f,y,g;const h=(p=(m=c.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(g=(y=c.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(h)?h.length:"not-array",argumentsDataPreview:u})});const a=s.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await Hd(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((c,d)=>{var u,m;const h=(m=(u=c.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const Tg=Object.freeze(Object.defineProperty({__proto__:null,action:Mg},Symbol.toStringTag,{value:"Module"})),$g=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function Ig({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return V({agents:[],error:d.error,search:r,page:1,totalPages:1});const h=d.total??(d.agents||[]).length,u=d.pageSize??20;return V({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(h/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),V({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function Rg(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 Dg(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 Lg(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function Xn({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 Og({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)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function Fg({content:e,truncated:t,fullLength:r}){const[s,a]=_(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!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 zg({entry:e,pairedResult:t}){const[r,s]=_(!1),a=Rg(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Xn,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Xn,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>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(nt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Mt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Xn,{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:a})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Og,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Fg,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Yg({context:e}){const[t,r]=_(!1);return l("div",{className:"my-2",children:[l("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(nt,{className:"w-3 h-3 text-gray-400"}):n(Mt,{className:"w-3 h-3 text-gray-400"}),n(Xn,{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 Bg({snippet:e}){const[t,r]=_(!1),s=e.split(`
|
|
274
|
-
`).filter(c=>c.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return l("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n(Gl,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),l("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((c,d)=>{const h=c.match(/^\[(\w+)\]:\s*(.*)/);if(!h)return null;const[,u,m]=h,p=u==="user";return l("div",{className:"text-xs",children:[l("span",{className:`font-bold ${p?"text-blue-700":"text-gray-500"}`,children:[p?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:m.length>200?m.slice(0,200)+"...":m})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function Ug({change:e}){const[t,r]=_(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(nt,{className:"w-3 h-3 inline flex-shrink-0"}):n(Mt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function Wg({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return l("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"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:"}),l("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,c)=>n(Ug,{change:i},c)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Hg({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",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,c=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return l("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[l("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),l("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&l("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&l("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&l("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&l("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&l("span",{children:["Input: ",c(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&l("span",{children:["Output: ",c(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&l("span",{children:["Cache read: ",c(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&l("span",{children:["Cache write:"," ",c(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,h)=>n("div",{className:"text-red-700 break-words",children:d},h))})]})]})}function Jg({agent:e,defaultOpen:t,isAdmin:r}){var C,S,A;const[s,a]=_(t),[o,i]=_(!1),[c,d]=_(null),[h,u]=_(!1),m=ae(()=>{const E={};for(const k of e.entries)k.type==="tool_result"&&k.tool_use_id&&(E[k.tool_use_id]=k);return E},[e.entries]),p=ae(()=>{const E=new Set;for(const k of e.entries)k.type==="tool_call"&&k.tool_use_id&&m[k.tool_use_id]&&E.add(k.tool_use_id);return E},[e.entries,m]),f=E=>{E.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(k=>k.json()).then(k=>{k.success?d(`Saved to ${k.fixturePath}`):d(`Error: ${k.error}`)}).catch(k=>{d(`Error: ${k instanceof Error?k.message:String(k)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(E=>E.action!=="touched"),g=y.filter(E=>E.action==="created"),x=y.filter(E=>E.action==="modified"),v=(e.ruleChanges||[]).filter(E=>E.action==="touched"),b=y.length>0,w=v.length>0,N=b||w;return l("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:[l("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(nt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Mt,{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:Lg(e.model)}),g.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(tr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(tr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&w&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&l("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(er,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),l("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&&l(ue,{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&&l(ue,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[Dg(e.timestamp),r&&b&&l("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(ql,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),c&&n("div",{className:`px-4 py-2 text-xs font-mono ${c.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:c}),s&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&l("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:E=>{E.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!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:h?n(ct,{className:"w-3.5 h-3.5 text-green-500"}):n(pt,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(Hg,{result:e.sessionResult}),e.stats.errors>0&&((A=e.stats.errorMessages)==null?void 0:A.length)>0&&l("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[l("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((E,k)=>n("li",{className:"break-words",children:E},k))})]}),e.conversationSnippet&&n(Bg,{snippet:e.conversationSnippet}),N&&n(Wg,{changes:e.ruleChanges}),e.context&&n(Yg,{context:e.context}),e.entries.map((E,k)=>{if(E.type==="tool_result"&&E.tool_use_id&&p.has(E.tool_use_id))return null;const j=E.type==="tool_call"&&E.tool_use_id?m[E.tool_use_id]:void 0;return n(zg,{entry:E,pairedResult:j},`${e.id}-${k}`)})]})]})}function ds(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 Vg=Ue(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=Je(),i=ft(),c=Al("root"),d=(c==null?void 0:c.isAdmin)??!1,[h,u]=_(s),[m,p]=_(!1),[f,y]=_(0);dt({source:"agent-transcripts-page"});const g=v=>{v.preventDefault(),window.location.href=ds(1,h)},x=()=>{p(!m),y(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Jl,{className:"w-5 h-5"})}),n(nr,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Pn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:h,onChange:v=>u(v.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:m?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&l("span",{children:[" ","matching “",s,"”",n(de,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(nr,{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(v=>n(Jg,{agent:v,defaultOpen:m,isAdmin:d},v.id))},f),o>1&&l("div",{className:"flex items-center justify-center gap-3 mt-8",children:[l("a",{href:a>1?ds(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>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(Vl,{className:"w-4 h-4"}),"Prev"]}),l("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),l("a",{href:a<o?ds(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"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(Mt,{className:"w-4 h-4"})]})]})]})})}),qg=Object.freeze(Object.defineProperty({__proto__:null,default:Vg,loader:Ig,meta:$g},Symbol.toStringTag,{value:"Module"}));function Gg(e){const t=e||process.cwd();try{return je("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 Kg(e){const t=e||process.cwd();try{return je("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Qg(e){if(Kg(e))return!1;je("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{je('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),je('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function Zg(e){je("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function Xg(e,t){return je(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Gg(e)}async function e0({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 a=Qg(s);a&&console.log("[editor-commit] Initialized new git repository"),Zg(s),console.log("[editor-commit] Staged all changes");const o=Xg(s,r);return console.log(`[editor-commit] Created commit: ${o}`),new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{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 t0=Object.freeze(Object.defineProperty({__proto__:null,action:e0},Symbol.toStringTag,{value:"Module"}));async function n0({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!io(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),h=io(r);if(h){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await Et({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function io(e){try{return process.kill(e,0),!0}catch{return!1}}const r0=Object.freeze(Object.defineProperty({__proto__:null,action:n0},Symbol.toStringTag,{value:"Module"})),s0=br(import.meta.url),a0=te.dirname(s0),o0=te.resolve(a0,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function i0(e){const t=[],r=new Set;for(const s of e.split(`
|
|
275
|
-
`)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const h=String(d.name||""),u=d.input||{};if(h==="Write"||h==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const p=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${h}:${p}`;r.has(f)||(r.add(f),t.push({action:h==="Write"?"created":"modified",filePath:p}))}}else if(h==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const p=`touch:${m}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:m}))}}}}return t}async function l0({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 Li(),a=s?te.join(Qn,s):null;let o=a?te.join(a,`${r}.log`):"";if((!o||!kt(o))&&(o=te.join(Qn,`${r}.log`)),!kt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await ys(o,"utf-8");let c=a?te.join(a,`${r}.context`):"";(!c||!kt(c))&&(c=te.join(Qn,`${r}.context`));let d=null;if(kt(c))try{d=await ys(c,"utf-8")}catch{}const h=i0(i),m=d?["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=>d.toLowerCase().includes(x)):!1,p=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+p,y=te.join(o0,f);await yc(y,{recursive:!0}),await bn(te.join(y,"agent-log.jsonl"),i),d&&await bn(te.join(y,"context.md"),d),await bn(te.join(y,"rule-changes.json"),JSON.stringify(h,null,2)),await bn(te.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:m,ruleChangeCount:h.length},null,2));const g=te.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 c0=Object.freeze(Object.defineProperty({__proto__:null,action:l0},Symbol.toStringTag,{value:"Module"}));async function d0({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=xe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=te.join(r,".codeyam","captures","screenshots",t);try{await ye.access(s);const a=await ye.readFile(s),o=te.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const u0=Object.freeze(Object.defineProperty({__proto__:null,loader:d0},Symbol.toStringTag,{value:"Module"})),lo={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 Zs({type:e,className:t=""}){const r=lo[e]||lo.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 h0={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 Jn({variant:e,pid:t,label:r,className:s=""}){const a=h0[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let co=!1;function m0(){if(co)return;const e=document.createElement("style");e.textContent=`
|
|
276
|
-
@keyframes strongPulse {
|
|
277
|
-
0%, 100% { opacity: 0.2; }
|
|
278
|
-
50% { opacity: 1; }
|
|
279
|
-
}
|
|
280
|
-
`,document.head.appendChild(e),co=!0}function Xs({size:e="medium",className:t=""}){typeof document<"u"&&m0();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:a,gap:o}=r[e];return l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}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 p0=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function f0({request:e,context:t,params:r}){var U,F,L,P,O,z,J,ee;let s=t.analysisQueue;s||(s=await vt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!s)return V({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=s.getState(),h=await Re();let u=null;if(h&&((U=d==null?void 0:d.currentlyExecuting)!=null&&U.commitSha)){const{project:Y,branch:D}=await De(h),W=await ir({projectId:Y.id,branchId:D.id,shas:[d.currentlyExecuting.commitSha]});u=W&&W.length>0?W[0]:null}else u=await on();const m=async Y=>{const D=await Ht(Y);if(!D)return null;const{getAnalysesForEntity:W}=await Promise.resolve().then(()=>iu),G=await W(Y,!1);return{...D,analyses:G||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async Y=>{const D=[];if(Y.entityShas&&Y.entityShas.length>0){const W=Y.entityShas.map(Z=>m(Z)),G=await Promise.all(W);D.push(...G.filter(Z=>Z!==null))}return{...Y,entities:D}}));let f=null;if(d!=null&&d.currentlyExecuting){const Y=d.currentlyExecuting,D=[];if(Y.entityShas&&Y.entityShas.length>0){const W=Y.entityShas.map(Z=>m(Z)),G=await Promise.all(W);D.push(...G.filter(Z=>Z!==null))}f={...Y,entities:D}}const y=f?p.filter(Y=>Y.id!==f.id):p,g=((L=(F=u==null?void 0:u.metadata)==null?void 0:F.currentRun)==null?void 0:L.currentEntityShas)||[],v=(await Promise.all(g.map(Y=>m(Y)))).filter(Y=>Y!==null),b=[];if(h)try{const{project:Y,branch:D}=await De(h),W=await ir({projectId:Y.id,branchId:D.id,limit:100});for(const G of W){const Z=((P=G.metadata)==null?void 0:P.historicalRuns)||[];b.push(...Z)}}catch(Y){console.error("[activity.tsx] Failed to load historical runs from commits:",Y)}const w=[...b].sort((Y,D)=>{const W=Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"";return(D.lastCaptureAt||D.analysisCompletedAt||D.archivedAt||D.createdAt||"").localeCompare(W)}),N=(o-1)*i,C=N+i,S=w.slice(N,C),A=Math.ceil(w.length/i),E=await Promise.all(S.map(async Y=>{const D=Y.currentEntityShas||[];if(D.length===0)return{...Y,entities:[]};const W=await Promise.all(D.map(G=>m(G)));return{...Y,entities:W.filter(G=>G!==null)}})),k=!!f,j=y.length,R=w.filter(Y=>{const D=!!Y.failedAt,W=Y.readyToBeCaptured,G=Y.capturesCompleted??0,Z=W===void 0?!0:W===0||G>=W;return!D&&!!Y.analysisCompletedAt&&Z}),M=new Set(((O=f==null?void 0:f.entities)==null?void 0:O.map(Y=>Y.sha))||[]),I=R.filter(Y=>!(Y.currentEntityShas||[]).some(W=>M.has(W))),T=(await Promise.all(I.slice(0,3).map(async Y=>{const D=Y.currentEntityShas||[];if(D.length===0)return{run:Y,entities:[]};const W=await Promise.all(D.map(G=>m(G)));return{run:Y,entities:W.filter(G=>G!==null)}}))).flatMap(({run:Y,entities:D})=>D.map(W=>({...W,runId:Y.id,completedAt:Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt})));let q=[],K=null,H=null;if((J=(z=u==null?void 0:u.metadata)==null?void 0:z.currentRun)!=null&&J.analysisCompletedAt&&v.length>0){const Y=v[0].sha;K=v[0];const D=await kr(Y);D&&D.length>0&&D[0].scenarios&&(q=D[0].scenarios,H=D[0].status)}return V({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(ee=u==null?void 0:u.metadata)==null?void 0:ee.currentRun,historicalRuns:E,totalHistoricalRuns:w.length,currentPage:o,totalPages:A,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:c,hasCurrentActivity:k,queuedCount:j,recentCompletedEntities:T,hasMoreCompletedRuns:I.length>3,currentEntityScenarios:q,currentEntityForScenarios:K,currentAnalysisStatus:H})}function g0({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{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:a.map(o=>{const i=e===o.id;return n(de,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
281
|
-
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
282
|
-
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
283
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
284
|
-
inline-block w-2 h-2 rounded-full
|
|
285
|
-
${i?"":"bg-gray-400"}
|
|
286
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function y0({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var $,T,q,K;const[m,p]=_({}),[f,y]=_({isKilling:!1,current:0,total:0}),g=lt(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),w=b&&!!(t!=null&&t.capturePid),N=!b,C=x,S=d||[],{lastLine:A}=yt(s,C);X(()=>{if(!t)return;const H=[t.analyzerPid,t.capturePid].filter(P=>!!P);if(H.length===0)return;let U=!0;const F=async()=>{try{const O=await(await fetch(`/api/process-status?pids=${H.join(",")}`)).json();if(O.processes&&U){const z={};O.processes.forEach(J=>{z[J.pid]={isRunning:J.isRunning,processName:J.processName}}),p(z)}}catch(P){U&&console.error("Failed to fetch process statuses:",P)}};F();const L=setInterval(()=>void F(),5e3);return()=>{U=!1,clearInterval(L)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[E,k]=_(!1),[j,R]=_(!1);X(()=>{v.length<=3&&E&&k(!1)},[v.length,E]),X(()=>{i.length<=3&&j&&R(!1)},[i.length,j]);const M=E?v:v.slice(0,3),I=v.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[C?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(at,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:w?"Capturing...":"Analyzing..."})]}),M.map(H=>l("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[l("div",{className:"flex items-center gap-3",children:[n("div",{children:n(Qe,{type:H.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(de,{to:`/entity/${H.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:H.name}),H.entityType&&n(Zs,{type:H.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:H.filePath,children:H.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},H.sha)),I&&!E&&l("button",{onClick:()=>k(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),E&&I&&n("button",{onClick:()=>k(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),w&&S&&S.length>0&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(H=>{var J,ee,Y,D;if(!H.id)return null;const U=(ee=(J=H.metadata)==null?void 0:J.screenshotPaths)==null?void 0:ee[0],F=(Y=H.metadata)==null?void 0:Y.noScreenshotSaved,L=U&&!F,P=(D=u==null?void 0:u.scenarios)==null?void 0:D.find(W=>W.name===H.name),z=P&&P.screenshotStartedAt&&!P.screenshotFinishedAt||!L&&!F;return n(de,{to:`/entity/${h.sha}/scenarios/${H.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:z?"#f9f9f9":void 0,borderColor:z?"#efefef":"#ccc"},children:L?n(Ve,{screenshotPath:U,alt:H.name,className:"w-full h-full object-contain bg-gray-100"}):z?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Xs,{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"})},H.id)})}),A&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Jn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(N||(($=m[t.analyzerPid])==null?void 0:$.isRunning))&&n(Jn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Jn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(w||((T=m[t.capturePid])==null?void 0:T.isRunning))&&n(Jn,{variant:"running"})]}),(((q=m[t==null?void 0:t.analyzerPid])==null?void 0:q.isRunning)||((K=m[t==null?void 0:t.capturePid])==null?void 0:K.isRunning))&&n("button",{onClick:()=>{const H=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(L=>{var P;return!!L&&((P=m[L])==null?void 0:P.isRunning)});if(H.length===0)return;const U=H.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${U})?`))return;y({isKilling:!0,current:1,total:H.length}),(async()=>{for(let L=0;L<H.length;L++){const P=H[L];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:P,commitSha:a||""})})}catch(O){console.error(`Failed to kill process ${P}:`,O)}L<H.length-1&&y({isKilling:!0,current:L+2,total:H.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Mo,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(de,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(de,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(j?i:i.slice(0,3)).map(H=>{var L;const U=(L=H.analyses)==null?void 0:L[0],F=(U==null?void 0:U.scenarios)||[];return U==null||U.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Qe,{type:H.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[n(de,{to:`/entity/${H.sha}`,className:"hover:underline cursor-pointer",title:H.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:H.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:H.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:H.filePath,children:H.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:P=>{P.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:P=>{P.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),F.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:F.map(P=>{var ee,Y,D;if(!P.id)return null;const O=(Y=(ee=P.metadata)==null?void 0:ee.screenshotPaths)==null?void 0:Y[0],z=(D=P.metadata)==null?void 0:D.noScreenshotSaved,J=O&&!z;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(de,{to:`/entity/${H.sha}/scenarios/${P.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:J?"#f3f4f6":"#FAFAFA",borderColor:J?"#d1d5db":"#BCCDD3",borderStyle:J?"solid":"dashed"},onMouseEnter:W=>{J&&(W.currentTarget.style.borderColor="#005C75",W.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:W=>{W.currentTarget.style.borderColor=J?"#d1d5db":"#BCCDD3",W.currentTarget.style.boxShadow="none"},children:J?n(Ve,{screenshotPath:O,alt:P.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:P.name})]},P.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},H.sha)}),i.length>3&&!j&&l("button",{onClick:()=>R(!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"]}),j&&i.length>3&&n("button",{onClick:()=>R(!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 x0({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Kl,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(de,{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,a]=_(null),[o,i]=_(null),[c,d]=_(null),[h,u]=_(!1),[m,p]=_(!1),[f,y]=_(new Set),g=lt();X(()=>{e.length<=3&&m&&p(!1)},[e.length,m]);const x=S=>{a(S)},v=(S,A)=>{S.preventDefault(),i(A)},b=async(S,A)=>{if(S.preventDefault(),!s){i(null);return}const E=e.findIndex(R=>R.id===s);if(E===-1){a(null),i(null);return}if(E===A){a(null),i(null);return}const k=E<A?"down":"up",j=Math.abs(A-E);u(!0);try{for(let R=0;R<j;R++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:k})});g.revalidate()}catch(R){console.error("Failed to reorder job:",R)}finally{u(!1),a(null),i(null)}},w=()=>{h||(a(null),i(null))},N=async S=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:S})}),window.location.reload()}catch(A){console.error("Failed to cancel job:",A)}},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 l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void 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"})]}),l("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(S=>{var I,$,T,q;const A=e.findIndex(K=>K.id===S.id),E=c===A,k=s===S.id,j=o===A,R=f.has(S.id),M=((I=S.entities)==null?void 0:I.length)>0?R?S.entities:S.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:k||h?.5:1,transform:j&&s!==null&&!k?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":k?"grabbing":"grab"},onMouseEnter:()=>d(A),onMouseLeave:()=>d(null),draggable:!h,onDragStart:K=>{x(S.id),K.dataTransfer.effectAllowed="move"},onDragOver:K=>v(K,A),onDrop:K=>void b(K,A),onDragEnd:w,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Ql,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",A+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[M.length>0?l(ue,{children:[M.map(K=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Qe,{type:K.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${K.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:K.name}),K.entityType&&n(Zs,{type:K.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:K.filePath})]})]})})},K.sha)),(($=S.entities)==null?void 0:$.length)>3&&n("button",{onClick:()=>{y(K=>{const H=new Set(K);return H.has(S.id)?H.delete(S.id):H.add(S.id),H})},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:R?"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:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(rr,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((T=S.entityNames)==null?void 0:T[0])||(S.type==="analysis"?"Analysis Job":S.type==="recapture"?"Recapture Job":S.type==="debug-setup"?"Debug Setup":S.type.charAt(0).toUpperCase()+S.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((q=S.filePaths)==null?void 0:q[0])||(S.filePaths&&S.filePaths.length>1?`${S.filePaths.length} files`:S.entityShas&&S.entityShas.length>0?`${S.entityShas.length} ${S.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[E&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Zl,{size:20})}),n("button",{onClick:()=>void N(S.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},S.id)}),e.length>3&&!m&&l("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),m&&e.length>3&&n("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function b0({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Xl,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=_(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{d.push({...m,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var y;const m=(y=u.analyses)==null?void 0:y[0],p=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(Qe,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(g=>{var w,N,C;if(!g.id)return null;const x=(N=(w=g.metadata)==null?void 0:w.screenshotPaths)==null?void 0:N[0],v=(C=g.metadata)==null?void 0:C.noScreenshotSaved,b=x&&!v;return n(de,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(Ve,{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)}),p.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>c(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const v0=Ue(function(){const t=Je(),r=Po(),[s,a]=_(!1);dt({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(g0,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(y0,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(x0,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(b0,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(At,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),w0=Object.freeze(Object.defineProperty({__proto__:null,default:v0,loader:f0,meta:p0},Symbol.toStringTag,{value:"Module"}));async function Wi(e,t,r){var N,C;await We();const s=await bt({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 a=xe();if(!a)throw new Error("Project root not found");const o=B.join(a,".codeyam","config.json"),i=JSON.parse(Q.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=_r(c);try{Q.writeFileSync(d,"","utf8")}catch{}const{project:h}=await De(c),u=((N=h.metadata)==null?void 0:N.packageManager)||"npm",m=3112,p=it(c),f=((C=h.metadata)==null?void 0:C.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=Ed({filePath:s.filePath,webapps:f,environmentVariables:y,port:m,packageManager:u});await an(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const A of S.scenarios)(!t||A.name===t)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t,prepOnly:!0}),v=g.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:c,port:m,packageManager:u,framework:g.framework,instructions:b}}async function C0({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return V({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await vt()),!o)return V({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Wi(s,a,o);return V({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),V({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function N0({request:e,context:t}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await vt()),!r)return V({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return V({error:"Missing required field: analysisId"},{status:400});const i=await Wi(a,o,r);return V({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),V({error:"Failed to setup debug environment",details:a},{status:500})}}const S0=Object.freeze(Object.defineProperty({__proto__:null,action:N0,loader:C0},Symbol.toStringTag,{value:"Module"})),k0=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Hi(e){const t=vc("sha256",k0);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function E0(e,t){return t===Hi(e)}async function A0({request:e}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return V({success:!1,error:"Unlock code is required"},{status:400});const s=await Re();return s?E0(s,r)?(await nn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),V({success:!0})):V({success:!1,error:"Invalid unlock code"},{status:400}):V({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),V({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const P0=Object.freeze(Object.defineProperty({__proto__:null,action:A0},Symbol.toStringTag,{value:"Module"}));async function _0({request:e,context:t}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await vt()),!r)return V({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return V({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return V({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const c=await ff(a,i,r);return console.log("[API] Recapture queued",c),V({success:!0,message:"Recapture queued",...c})}catch(s){return console.log("[API] Error during recapture:",s),V({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const j0=Object.freeze(Object.defineProperty({__proto__:null,action:_0},Symbol.toStringTag,{value:"Module"}));function M0(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(T0).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let c=0;c<Math.min(a.length,o.length)&&a[c]===o[c];c++)i.push(a[c]);return i}).join("/")}function T0(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if($0(s))r.pop();else break}return r.join("/")}function $0(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function I0({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=M0(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const R0=Object.freeze(Object.defineProperty({__proto__:null,loader:I0},Symbol.toStringTag,{value:"Module"}));function D0(e,t){var i,c,d,h,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?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 a=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||a){const m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}: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 L0(e){return D0(e).hasOutdatedSimulations}function Fr(e,t,r,s,a){var K,H,U,F,L,P,O,z;const o=(K=t==null?void 0:t.scenarios)==null?void 0:K.find(J=>J.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,m=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((U=(H=e.metadata)==null?void 0:H.screenshotPaths)!=null&&U[0])||!!((F=e.metadata)!=null&&F.executionResult),f=c&&!d,y=o==null?void 0:o.error,g=(P=(L=e.metadata)==null?void 0:L.executionResult)==null?void 0:P.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const J of t.errors)x.push({source:`${J.phase} phase`,message:J.message});if(t!=null&&t.steps)for(const J of t.steps)J.error&&x.push({source:J.name,message:J.error});const v=!p&&!y&&!g&&x.length>0,b=!!(y||g||m||v),w=m?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(v?`Analysis error: ${x[0].message}`:null),N=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,S=(s&&a?a.jobs.some(J=>{var ee;return((ee=J.entityShas)==null?void 0:ee.includes(s))||J.type==="analysis"&&J.entityShas&&J.entityShas.length===0})||((z=(O=a.currentlyExecuting)==null?void 0:O.entityShas)==null?void 0:z.includes(s)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,A=i&&!c&&!h&&!b,E=(S||A||f)&&!b,k=(S||A)&&r===!1&&!p;let j;k?j="crashed":b?j="error":p||h?j="completed":f?j="capturing":A?j="starting":S?j="queued":j="pending";let R="📷",M="pending",I=!1,$=`Not captured: ${e.name}`;const T="border-gray-300",q=b||k?"bg-red-50":"bg-white";return b||k?(R="⚠️",M="error",$=`Error: ${k?"Analysis process crashed":w||"Unknown error"}`):S?(R="⋯",M="queued",$=`Queued: ${e.name}`):A?(R="⋯",M="starting",I=!0,$=`Starting server for ${e.name}...`):f&&!b?(R="⋯",M="capturing",I=!0,$=`Capturing ${e.name}...`):p&&(R="✓",M="completed",$=e.name),{hasError:b||k,errorMessage:k?"Analysis process crashed":w,errorStack:k?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:p,hasCrashed:k,isAnalyzing:E,isQueued:S,isServerStarting:A,status:j,icon:R,iconType:M,shouldSpin:I,title:$,borderColor:T,bgColor:q}}function Ji({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var N,C,S,A,E,k;const o=Fr(e,void 0,void 0,t,void 0),i=(N=e.metadata)==null?void 0:N.executionResult,c=!!i,h=(((S=(C=e.metadata)==null?void 0:C.data)==null?void 0:S.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((E=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:E.length)||0,p=((k=i==null?void 0:i.timing)==null?void 0:k.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=s?`border-2 ${x.border}`:"",b=Array.from({length:3},(j,R)=>n("div",{className:`w-1 h-1 rounded-full ${R<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},R)),w=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
|
|
287
|
-
${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
|
|
288
|
-
${p}ms`:`Not executed: ${e.name}`;return l(de,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:w,onClick:j=>j.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!o.hasError&&m>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function Ms({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function uo({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var g,x;if(t.entityType==="library")return n(Ji,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Fr(e,r,a,t.sha,s),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${c}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(de,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ve,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(Xs,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Ms,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(ec,{...v});default:return b}};return n(de,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:m.iconSize,children:y()})})}const Qt=70;function O0({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:y,isBreakdownView:g}){var I,$,T,q,K,H;const x=be(null),[v,b]=_(new Set),[w,N]=_(!1);X(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const C=U=>`/entity/${a}/scenarios/${U}`,S=U=>{b(F=>{const L=new Set(F);return L.has(U)?L.delete(U):L.add(U),L})},A=(U,F=2)=>{const P=U.split(`
|
|
289
|
-
`).slice(0,F).join(" ").trim();return P.length>Qt?P.substring(0,Qt-3):(U.split(`
|
|
290
|
-
`).length>F||U.length>P.length,P)},E=ae(()=>{var F;if(!((F=r==null?void 0:r.metadata)!=null&&F.executionFlows)||!(r!=null&&r.scenarios))return null;const U=r.scenarios.filter(L=>{var P;return!((P=L.metadata)!=null&&P.sameAsDefault)});return qs(r.metadata.executionFlows,U)},[r]),k=(E==null?void 0:E.totalFlows)||0,j=(E==null?void 0:E.coveredFlows)||0,R=(E==null?void 0:E.coveragePercentage)||0;(I=d==null?void 0:d.metadata)!=null&&I.defaultWidth||($=r==null?void 0:r.metadata)!=null&&$.defaultWidth;const M=(T=r==null?void 0:r.status)!=null&&T.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(R),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((K=e[0])==null?void 0:K.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[j,"/",k]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((H=e[0])==null?void 0:H.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(de,{to:`/entity/${a}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),M&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:M})]}),m&&(p||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((U,F)=>{const L=!g&&(s==null?void 0:s.id)===U.id,P=v.has(U.id||"");return U.id?l(de,{to:C(U.id),ref:L?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${L?"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(uo,{scenario:U,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${P?"":"line-clamp-1"}`,children:U.name}),U.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[P?U.description:A(U.description),!P&&U.description.length>Qt&&l(ue,{children:["...",n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),S(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),P&&U.description.length>Qt&&n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),S(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},F):null})})}),t.length>0&&!(m&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>N(!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&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((U,F)=>{const L=!g&&(s==null?void 0:s.id)===U.id,P=v.has(U.id||"");return U.id?l(de,{to:`/entity/${a}/scenarios/${U.id}`,ref:L?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${L?"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(uo,{scenario:U,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${P?"":"line-clamp-1"}`,children:U.name}),U.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[P?U.description:A(U.description),!P&&U.description.length>Qt&&l(ue,{children:["...",n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),S(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),P&&U.description.length>Qt&&n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),S(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},F):null})})]})]})]})}function F0({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,y]=_(""),g=async()=>{await r(f)},x=async v=>{await s(f,v),v||y("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(de,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>y(v.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),l("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(de,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:c?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&l(ue,{children:[h?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function z0({scenario:e,analysis:t,entity:r}){var i,c,d;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=h=>{var y,g,x;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((y=h.sideEffects)==null?void 0:y.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const p=((g=h.sideEffects)==null?void 0:g.fileWrites)||[];p.length>0&&(u.push(`
|
|
291
|
-
File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=h.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
292
|
-
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),h.error&&u.push(`
|
|
293
|
-
Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
294
|
-
`)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children: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"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const Ft={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Vn({scenarioId:e,analysisId:t}){const[r,s]=_(!1),[a,o]=_(!1),[i,c]=_(null),[d,h]=_(!1),u=e||t;if(!u)return null;const m=`/codeyam-diagnose ${u}`,p=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),c(null)};return l(ue,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Ft.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:Ft.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Ft.commandBoxBg,borderColor:Ft.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:Ft.commandBoxText},children:m}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":Ft.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(ct,{size:14}):n(pt,{size:14})})]}),l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:a,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:Ft.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(Fo,{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 ho=1440,qn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],ht={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Vi({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var G,Z,re,ge,ve,Ne,Ee,Te,$e,Ie,Oe;const m=Le(),[p,f]=_(!1),[y,g]=_(!1),[x,v]=_({name:"Desktop",width:ho,height:900}),[b,w]=_(ho),[N,C]=_(1),{customSizes:S,addCustomSize:A,removeCustomSize:E}=Rr(c),k=ae(()=>[...qn,...S],[S]),j=(Se,ne)=>{w(Se);const he=k.find(ke=>ke.width===Se&&ke.height===ne);v({name:(he==null?void 0:he.name)||"Custom",width:Se,height:ne})},R=Se=>{w(Se.width),v({name:Se.name,width:Se.width,height:Se.height})},M=Se=>{A(Se,x.width,x.height??900),g(!1),v(ne=>({...ne,name:Se}))},I=(Se,ne)=>{w(Se);const he=k.find(ke=>ke.width===Se&&ke.height===ne);v(ke=>({name:(he==null?void 0:he.name)||"Custom",width:Se,height:ke.height}))},$=(Z=(G=e==null?void 0:e.metadata)==null?void 0:G.screenshotPaths)==null?void 0:Z[0],T=ae(()=>e?Fr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),q=ae(()=>{var ne,he;const Se=[];if((ne=t==null?void 0:t.status)!=null&&ne.errors&&t.status.errors.length>0)for(const ke of t.status.errors)Se.push({source:`${ke.phase} phase`,message:ke.message,stack:ke.stack});if((he=t==null?void 0:t.status)!=null&&he.steps)for(const ke of t.status.steps)ke.error&&Se.push({source:ke.name,message:ke.error,stack:ke.errorStack});return Se},[(re=t==null?void 0:t.status)==null?void 0:re.errors,(ge=t==null?void 0:t.status)==null?void 0:ge.steps]),K=(T==null?void 0:T.errorMessage)||null,H=(T==null?void 0:T.errorStack)||null,{interactiveServerUrl:U,isStarting:F,isLoading:L,showIframe:P,iframeKey:O,onIframeLoad:z}=qt({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:s==="interactive"}),J=ae(()=>U||null,[U]),ee=!i&&o&&e&&!((Ne=(ve=e.metadata)==null?void 0:ve.screenshotPaths)!=null&&Ne[0])&&((Te=(Ee=t==null?void 0:t.status)==null?void 0:Ee.scenarios)==null?void 0:Te.some(Se=>Se.name===e.name&&Se.screenshotStartedAt&&!Se.screenshotFinishedAt)),{lastLine:Y}=yt(c,i||s==="interactive"||ee||!1);if(!e){if(i&&r)return l(ue,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:ee?"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."}),Y&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:Y}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&n(At,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(q.length>0){const Se=q.length===1?(($e=q[0])==null?void 0:$e.message)||"An error occurred during analysis.":`${q.length} errors occurred during analysis.`;return l(ue,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:ht.background,border:`2px solid ${ht.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(Ms,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:ht.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",Se," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:ht.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Vn,{analysisId:t==null?void 0:t.id})})]})}),p&&c&&n(At,{projectSlug:c,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(ue,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
295
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
296
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
297
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
298
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
299
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||ee&&!$)&&!K&&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:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:ee?`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:ee?`Taking screenshots for ${((Ie=t==null?void 0:t.scenarios)==null?void 0:Ie.length)||0} scenario${((Oe=t==null?void 0:t.scenarios)==null?void 0:Oe.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),Y&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:Y,children:Y})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&($||K)||s==="interactive"&&(J||F)||s==="data"?l(ue,{children:[K&&!$&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:ht.background,border:`2px solid ${ht.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:ht.text},children:[n(Ms,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:ht.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:ht.text},children:K})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Vn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[J&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n($h,{presets:[...qn],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:N,onSizeChange:j,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:E}),e&&r&&l(de,{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"]})]}),J&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${qn[qn.length-1].width}px`,width:"100%"},children:n($r,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:R,devicePresets:k})})}),n(Lr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:J,isStarting:F,isLoading:L,showIframe:P,iframeKey:O,onIframeLoad:z,onScaleChange:C,onDimensionChange:I,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(z0,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:($||!K)&&n(Ve,{screenshotPath:$,cacheBuster:a,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&&!$?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),Y&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:Y})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):K?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(de,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:K})})]}),H&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:H})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Vn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):q.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:q,title:"Analysis Error",description:q.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${q.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Vn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&n(At,{projectSlug:c,onClose:()=>f(!1)}),y&&n(Ir,{width:x.width,height:x.height??900,onSave:M,onCancel:()=>g(!1)})]})}function Y0({analysis:e,entitySha:t}){lt();const[r,s]=_(e);X(()=>{s(e)},[e]);const[a,o]=_(null),i=ae(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return qs(r.metadata.executionFlows,u)},[r]),c=ae(()=>i?cm(i):[],[i]),d=ae(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),h=u=>{var p;const m=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(de,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const m=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],p=h(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ve,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(de,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(de,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=a===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(m?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:l("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),m&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),p&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function mo({hasIndirectBadge:e,onAnalyze:t}){return l(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function B0({entity:e,history:t}){const[r,s]=_("entity"),[a,o]=_(new Set),i=t.filter(u=>u.analyses.length>0).length,c=ae(()=>{const u=new Map;return t.forEach(m=>{m.analyses.forEach(p=>{(p.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:m,analysis:p,scenario:y})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,h=u=>{o(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>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})]}),l("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:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,m)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(de,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var g;const y=(p.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(mo,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=p.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,v)=>{var N,C;const b=(C=(N=x.metadata)==null?void 0:N.screenshotPaths)==null?void 0:C[0],w=`${x.name}-${v}`;return l(de,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Ve,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},w)})})})]})},p.id||f)})}):n(mo,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,m)=>{const p=a.has(u.name),f=p?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var A,E;const{version:b,analysis:w,scenario:N}=x,C=(E=(A=N.metadata)==null?void 0:A.screenshotPaths)==null?void 0:E[0],S=v===0;return l("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(de,{to:`/entity/${b.sha}/scenarios/${N.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:C?n(Ve,{screenshotPath:C,alt:N.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),S&&u.versions.length>1&&l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),l(de,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),w.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(w.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),w.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),y>0&&l("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function po({entity:e,analysisInfo:t,from:r}){const s=Le(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(de,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:l("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ve,{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(Qe,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Qe,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const fo=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.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 U0({importedEntities:e,importingEntities:t}){const[r]=sn(),s=r.get("from"),a=Le(),o=a.state!=="idle",i=e.length>0,c=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=p=>{const f=d(p);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,m=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(po,{entity:p,analysisInfo:fo(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(po,{entity:p,analysisInfo:fo(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function W0({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(U0,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function H0({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(An,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function An({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,c]=_(r||t<2);if(X(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>n("div",{className:"py-0.5",children:n(An,{data:h,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[h.length,"}"]})]}),i?l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],y=u(f),g=m(f);return n("div",{className:"py-0.5",children:y?n(ea,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(ta,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):l(ue,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),n(An,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function ea({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2),c=Object.keys(t);return X(()=>{i(s||r<2)},[s,r]),l(ue,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n(ea,{propertyKey:d,value:h,depth:r+1,defaultExpanded:s,maxDepth:a}):m?n(ta,{propertyKey:d,value:h,depth:r+1,defaultExpanded:s,maxDepth:a}):l(ue,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(An,{data:h,depth:r+2,defaultExpanded:s,maxDepth:a})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function ta({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2);return X(()=>{i(s||r<2)},[s,r]),l(ue,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const h=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:h?n(ea,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(ta,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):n(An,{data:c,depth:r+2,defaultExpanded:s,maxDepth:a})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function us({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return l("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?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function go({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 yo({call:e,scenarioName:t}){const[r,s]=_(!1),[a,o]=_("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const y=[];return p&&y.push(`${p.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},h=ae(()=>{var p,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(p=v.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&y.content?v.choices[0].message.content:(x=(g=v.content)==null?void 0:g[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=ae(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=ae(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="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"})}),a==="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})}),a==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const xo=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function J0({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var w,N,C,S,A,E,k,j,R;const[o,i]=_("entity"),[c,d]=_("analysis"),[h,u]=_(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=_("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ae(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const M=[...a.entityCalls,...a.analysisCalls],I=M.filter(T=>T.object_type==="entity"||xo.includes(T.prompt_type)),$=M.filter(T=>T.object_type!=="entity"&&!xo.includes(T.prompt_type));return I.sort((T,q)=>q.created_at-T.created_at),$.sort((T,q)=>q.created_at-T.created_at),{entityLlmCalls:I,scenarioLlmCalls:$,totalLlmCalls:M.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(w=e==null?void 0:e.metadata)==null?void 0:w.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.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:(A=t==null?void 0:t.metadata)==null?void 0:A.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(E=e==null?void 0:e.metadata)==null?void 0:E.importedExports,"External Dependencies":(k=e==null?void 0:e.metadata)==null?void 0:k.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(j=t==null?void 0:t.metadata)==null?void 0:j.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(M=>M.data!==void 0&&M.data!==null).length;let b=null;if(o==="entity"){const M=x.find(I=>I.id===c);M&&M.data!==void 0&&M.data!==null&&(b={title:M.title,description:M.description,data:M.data})}else if(o==="scenarios"&&h){const M=r.find(I=>(I.id||I.name)===h.scenarioId);M&&(b={title:M.name,description:M.description||"Scenario data and configuration",data:M.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n(us,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(us,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(us,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((R=t==null?void 0:t.metadata)==null?void 0:R.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(M=>n(yo,{call:M},M.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(M=>n(yo,{call:M},M.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(M=>{const I=M.data!==void 0&&M.data!==null;return n(go,{label:M.title,isActive:c===M.id,onClick:()=>d(M.id),disabled:!I},M.id)})})]}):l(ue,{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(M=>{const I=M.id||M.name,$=(h==null?void 0:h.scenarioId)===I;return n(go,{label:M.name,isActive:$,onClick:()=>u({scenarioId:I})},I)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(V0,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(bo,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(bo,{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 bo({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function V0({title:e,description:t,data:r}){const[s,a]=_(!0);return l(ue,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!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:()=>a(!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(dn,{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(H0,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function q0({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Le();return X(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(J0,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const G0={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},K0={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Q0=2e3,Z0=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 X0({entity:e,entityCode:t}){const r=gr(),s=be(null);return X(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const c=s.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(dn,{content:t,label:"Copy Code",duration:Q0,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(Tc,{language:Z0(e==null?void 0:e.filePath),style:$c,showLineNumbers:!0,customStyle:G0,lineNumberStyle:K0,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const ey=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function ty({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function ny({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",h=c[1]||null,u=c[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Ht(s),Re(),on(),cu(xe()||process.cwd())]),v=f?await Er(f):null,b=f?await ti(f.sha):null;let w={importedEntities:[],importingEntities:[]},N=null,C=[];f&&(w=await ni(f),N=await ri(f),C=await ai(f));const S=!!(f&&C.length>0&&C[0].sha!==f.sha),A=C.length>0?C[0].sha:null,E=!!(C.length>0&&C[0].analyses&&C[0].analyses.length>0),k=f?await si(f):!1;return V({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:o,relatedEntities:w,entityCode:N??void 0,hasNewerVersion:S,newestEntitySha:A,newestVersionHasAnalysis:E,fileModifiedSinceEntity:k,history:C,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:p})}const ry=Ue(function(){var ma,pa,fa,ga,ya,xa,ba,va,wa,Ca,Na,Sa,ka,Ea,Aa;const t=Je(),a=(Po()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,c=a[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,m=u||h,p=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,w=t.history,N=t.currentCommit,C=t.hasAnApiKey,S=t.queueState;(ma=m==null?void 0:m.status)==null||ma.errors;const A=(m==null?void 0:m.scenarios)||[],E=A.filter(ce=>{var Pe;return!((Pe=ce.metadata)!=null&&Pe.sameAsDefault)}),k=A.filter(ce=>{var Pe;return(Pe=ce.metadata)==null?void 0:Pe.sameAsDefault}),j=ft(),R=be(null);X(()=>{R.current===null&&(R.current=window.history.length)},[]);const M=()=>{if(typeof window>"u")return;const ce=window.history.state;if(ce===null||(ce==null?void 0:ce.idx)===void 0||(ce==null?void 0:ce.idx)===0)j("/");else{const Pe=window.history.length,Ke=R.current;if(Ke!==null&&Pe>Ke){const Fe=Pe-Ke+1;j(-Fe)}else j(-1)}},I=!!S.currentlyExecuting,$=o,T=(pa=N==null?void 0:N.metadata)==null?void 0:pa.currentRun,q=!!(T!=null&&T.createdAt)&&!(T!=null&&T.analysisCompletedAt),K=!!(d!=null&&d.sha&&((fa=T==null?void 0:T.currentEntityShas)!=null&&fa.includes(d.sha))),H=!!(d!=null&&d.sha&&((ya=(ga=S.currentlyExecuting)==null?void 0:ga.entityShas)!=null&&ya.includes(d.sha))),U=!!(d!=null&&d.sha&&((xa=S.jobs)!=null&&xa.some(ce=>{var Pe;return(Pe=ce.entityShas)==null?void 0:Pe.includes(d.sha)}))),F=K||H||U,L=F&&((ba=m==null?void 0:m.status)==null?void 0:ba.finishedAt)!=null&&E.length>0&&m.entitySha!==(d==null?void 0:d.sha),P=ae(()=>{if($!=="scenarios")return null;if(i){const ce=E.find(Pe=>Pe.id===i);if(ce)return ce}return E.length>0&&!F?E[0]:null},[$,i,E,F]),O=((Ca=(wa=(va=P==null?void 0:P.metadata)==null?void 0:va.executionResult)==null?void 0:wa.error)==null?void 0:Ca.message)||((ka=(Sa=(Na=m==null?void 0:m.status)==null?void 0:Na.errors)==null?void 0:Sa[0])==null?void 0:ka.message);dt({source:P?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:P==null?void 0:P.id,analysisId:m==null?void 0:m.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:P==null?void 0:P.name,errorMessage:O});const[z,J]=_(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");X(()=>{c&&c!==z&&c!=="edit"&&J(c)},[c]);const ee=c==="edit",[Y,D]=_(!1),[W,G]=_(!1),[Z,re]=_(null),[ge,ve]=_(!1),[Ne,Ee]=_(!1),[Te,$e]=_(null),[Ie,Oe]=_(null),[Se,ne]=_(0),{interactiveServerUrl:he,isStarting:ke,isLoading:rt,showIframe:fe,iframeKey:ze,onIframeLoad:Be}=qt({analysisId:m==null?void 0:m.id,scenarioId:P==null?void 0:P.id,scenarioName:P==null?void 0:P.name,projectSlug:p,enabled:ee&&!!P,refreshTrigger:Se}),[It,$n]=_(!1),[Br,da]=_(""),[Rt,Dt]=_(!1),[In,un]=_(Date.now()),[Ur,Gt]=_(!1),se=Le(),le=Le(),me=Le(),we=lt(),He=S.jobs.some(ce=>{var Pe;return(d==null?void 0:d.sha)&&((Pe=ce.entityShas)==null?void 0:Pe.includes(d.sha))||ce.type==="analysis"&&ce.commitSha===(N==null?void 0:N.sha)&&ce.entityShas&&ce.entityShas.length===0}),wt=F,Rn=((Ea=d==null?void 0:d.metadata)==null?void 0:Ea.defaultWidth)||((Aa=m==null?void 0:m.metadata)==null?void 0:Aa.defaultWidth)||1440,hn=Math.round(Rn*(900/1440));se.state==="submitting"||se.state,ae(()=>{var ce;return!!((ce=P==null?void 0:P.metadata)!=null&&ce.interactiveExamplePath)},[P]);const{isCompleted:ua}=yt(p,Rt);X(()=>{se.state==="idle"&&se.data&&(se.data.success?setTimeout(()=>{un(Date.now()),we.revalidate(),Dt(!1)},1500):se.data.error&&(Dt(!1),alert(`Recapture failed: ${se.data.error}`)))},[se.state,se.data,we]),X(()=>{Rt&&ua&&setTimeout(()=>{un(Date.now()),we.revalidate(),Dt(!1)},1500)},[Rt,ua,we]),X(()=>{le.state==="idle"&&le.data&&(le.data.success?setTimeout(()=>{un(Date.now()),we.revalidate(),Dt(!1)},1500):le.data.error&&(Dt(!1),alert(`Recapture failed: ${le.data.error}`)))},[le.state,le.data,we]);const ha=()=>{d&&(g&&x&&x!==d.sha?(j(`/entity/${x}/scenarios`),setTimeout(()=>{me.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):me.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};X(()=>{me.state==="idle"&&me.data&&(me.data.success?we.revalidate():me.data.error&&alert(`Analysis failed: ${me.data.error}`))},[me.state,me.data,d==null?void 0:d.sha,we]),X(()=>{const ce=setTimeout(()=>{we.revalidate()},500);return()=>clearTimeout(ce)},[]),X(()=>{if(q||wt){const ce=setInterval(()=>{we.revalidate()},3e3);return()=>clearInterval(ce)}},[q,wt,we]);const ll=(ce,Pe)=>ce==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ce}`,cl=(ce,Pe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ce}/${Pe}`,dl=ce=>{J(ce),P!=null&&P.id&&(ce==="interactive"?j(`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/fullscreen`,{replace:!0}):j(cl(P.id,ce),{replace:!0}))},ul=async ce=>{var Pe,Ke;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ce,hasSelectedScenario:!!P,hasAnalysis:!!m}),!P||!m){const Fe="Error: No scenario or analysis available";console.error("[EntityDetail]",Fe),re(Fe);return}D(!0),re(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ce,scenarioId:P.id,scenarioName:P.name,currentData:P.data});try{const Fe=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ce,existingScenarios:m.scenarios,scenariosDataStructure:(Pe=m.metadata)==null?void 0:Pe.scenariosDataStructure,editingMockName:P.name,editingMockData:Ie||((Ke=P.metadata)==null?void 0:Ke.data)})}),ut=await Fe.json();if(!Fe.ok||!ut.success)throw new Error(ut.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",ut.data),Oe(ut.data);const Dn=(m.scenarios||[]).map(Ge=>Ge.id===P.id?{...Ge,metadata:{...Ge.metadata,data:ut.data}}:Ge),mn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:Dn})}),Xe=await mn.json();if(!mn.ok||!Xe.success)throw console.error("[EntityDetail] Temp save failed:",Xe),new Error(Xe.error||"Failed to apply preview");if(re("Generating preview. Capturing screenshot..."),he){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:he});const Ge=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:he,scenarioId:P.id,projectId:m.projectId,viewportWidth:1440})}),pn=await Ge.json();!Ge.ok||!pn.success?(console.error("[EntityDetail] Direct capture failed:",pn),re("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),re('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ge=new FormData;Ge.append("analysisId",m.id||""),Ge.append("scenarioId",P.id||"");const pn=await fetch("/api/recapture-scenario",{method:"POST",body:Ge}),Hr=await pn.json();!pn.ok||!Hr.success?(console.warn("[EntityDetail] Recapture failed:",Hr.error),re("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Hr.jobId),re('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ne(Ge=>Ge+1),we.revalidate()}catch(Fe){console.error("Error applying changes:",Fe),re(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{D(!1)}},hl=async(ce,Pe)=>{var Ke;if(!P||!m){re("Error: No scenario or analysis available");return}G(!0),re(null),console.log("[EntityDetail] Saving scenario to database",{description:ce,saveAsNew:Pe});try{const Fe=Ie||((Ke=P.metadata)==null?void 0:Ke.data);let ut;if(Pe){const Xe={...P,id:`${P.name}-${Date.now()}`,name:`${P.name} (Copy)`,metadata:{...P.metadata,data:Fe},description:ce||P.description};ut=[...m.scenarios||[],Xe]}else ut=(m.scenarios||[]).map(Xe=>Xe.id===P.id?{...Xe,metadata:{...Xe.metadata,data:Fe},description:ce||Xe.description}:Xe);const Dn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:ut})}),mn=await Dn.json();if(!Dn.ok||!mn.success)throw new Error(mn.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),re(Pe?"New scenario created successfully":"Scenario saved successfully"),Oe(null),we.revalidate()}catch(Fe){console.error("Error saving scenario:",Fe),re(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{G(!1)}},ml=()=>{P!=null&&P.id&&(d!=null&&d.sha)&&j(`/entity/${d.sha}/scenarios/${P.id}/dev`)},pl=async()=>{var ce;if(!(P!=null&&P.id)){$e("Cannot delete scenario without ID");return}ve(!0),$e(null);try{const Pe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:P.id,screenshotPaths:((ce=P.metadata)==null?void 0:ce.screenshotPaths)||[]})}),Ke=await Pe.json();if(!Pe.ok||!Ke.success)throw new Error(Ke.error||"Failed to delete scenario");j(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(Pe){console.error("[EntityDetail] Error deleting scenario:",Pe),$e(Pe instanceof Error?Pe.message:"Failed to delete scenario"),Ee(!1)}finally{ve(!1)}},Wr=m&&d&&m.entitySha!==d.sha,fl=d?L0(d):!1;return n(Dr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:M,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:E.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(ce=>n(de,{to:ll(ce.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${$===ce.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:$===ce.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[ce.label,ce.count!==void 0&&ce.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${$===ce.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ce.count})]})},ce.id))})]})}),(g||Wr&&!u||b&&fl)&&!F&&!He&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Wr&&!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.":Wr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&v?n(de,{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:ce=>{ce.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ce=>{ce.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:ha,disabled:me.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:ce=>{me.state==="idle"&&(ce.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ce=>{me.state==="idle"&&(ce.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[$==="scenarios"&&l(ue,{children:[ee&&P?n(F0,{scenario:P,entitySha:(d==null?void 0:d.sha)||"",onApply:ul,onSave:hl,onEditMockData:ml,onDelete:pl,isApplying:Y,isSaving:W,saveMessage:Z,showDeleteConfirm:Ne,onShowDeleteConfirm:Ee,isDeleting:ge,deleteError:Te}):n(O0,{scenarios:E,hiddenScenarios:k,analysis:m,selectedScenario:P,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:In,activeTab:$,entityType:d==null?void 0:d.entityType,entity:d,queueState:S,processIsRunning:I,isEntityAnalyzing:F,areScenariosStale:L,viewMode:z,setViewMode:dl,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Y0,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):ee&&P?n(Lr,{scenarioId:P.id||P.name,scenarioName:P.name,iframeUrl:he,isStarting:ke,isLoading:rt,showIframe:fe,iframeKey:ze,onIframeLoad:Be,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[P&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:P.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Rn," × ",hn]})]}),l("div",{className:"flex items-center gap-2",children:[n(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.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:[l("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"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.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(Vi,{selectedScenario:P,analysis:m,entity:d,viewMode:z,cacheBuster:In,hasScenarios:E.length>0,isAnalyzing:wt,projectSlug:p,hasAnApiKey:C,processIsRunning:I,queueState:S})]})]}),$==="related"&&n(W0,{relatedEntities:f}),$==="data"&&n(q0,{entity:d,analysis:m,scenarios:E,onAnalyze:ha}),$==="code"&&n(X0,{entity:d,entityCode:y}),$==="history"&&n(B0,{entity:d,history:w})]}),Ur&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Gt(!1),children:l("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ce=>ce.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>Gt(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(At,{projectSlug:p,onClose:()=>Gt(!1)})})]})})]})})}),sy=Object.freeze(Object.defineProperty({__proto__:null,default:ry,loader:ny,meta:ey,shouldRevalidate:ty},Symbol.toStringTag,{value:"Module"}));async function ay(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await We();const i=xe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=te.join(i,".codeyam","config.json"),d=JSON.parse(await ye.readFile(c,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=_r(h);try{await ye.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await De(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await ot({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const x=await ou(p,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Et({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const w=b.currentRun;if(w&&w.id&&w.archivedAt)return;w&&(w.analysesCompleted&&w.analysesCompleted>0||w.capturesCompleted&&w.capturesCompleted>0)&&yu(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:h,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function oy({request:e,context:t}){if(e.method!=="POST")return V({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await vt()),!r)return V({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),c=s.get("context"),d=s.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(a)h=[a];else return V({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return V({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await ot({shas:h}),p=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await ay({entityShas:h,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),V({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),V({error:"Failed to start analysis",details:s.message},{status:500})}}const iy=Object.freeze(Object.defineProperty({__proto__:null,action:oy},Symbol.toStringTag,{value:"Module"}));function ly(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function qi(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 a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",c=a%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function et(e,t=[],r=!1){var u,m;if(t.some(p=>{var f,y;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(y=p.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,c=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=a.scenarios||[],h=d.some(p=>{var f,y,g;return((y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=p.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&h?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const cy=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function dy({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await Vt();return V({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),V({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const uy=Ue(function(){const t=Je(),r=t.entities,s=t.queueState;dt({source:"simulations-page"});const[a,o]=_(""),[i,c]=_("visual"),d=ae(()=>{const g=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const w=v.scenarios.filter(N=>{var C;return!((C=N.metadata)!=null&&C.sameAsDefault)}).map(N=>{var R,M,I,$,T;const C=(M=(R=N.metadata)==null?void 0:R.screenshotPaths)==null?void 0:M[0],S=(I=N.metadata)==null?void 0:I.noScreenshotSaved,A=C&&!S,E=(T=($=v.status)==null?void 0:$.scenarios)==null?void 0:T.find(q=>q.name===N.name),k=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt;let j;return A?j="completed":k?j="capturing":j="error",{scenarioName:N.name,scenarioDescription:N.description||"",screenshotPath:C||"",scenarioId:N.id,state:j}}).filter(N=>N.state==="completed"||N.state==="capturing");w.length>0&&g.push({entity:x,screenshots:w,createdAt:v.createdAt||""})}}),g.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),h=ae(()=>r.filter(g=>{var b,w;const x=(b=g.analyses)==null?void 0:b[0];return!((w=x==null?void 0:x.scenarios)==null?void 0:w.some(N=>{var C,S;return(S=(C=N.metadata)==null?void 0:C.screenshotPaths)==null?void 0:S[0]}))}),[r]),u=ae(()=>d.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[d,a,i]),m=ae(()=>h.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[h,a,i]),p=ie(g=>{o(g.target.value)},[]),f=ie(g=>{c(g.target.value)},[]),y=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(nt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(Pn,{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:a,onChange:p})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:u.map(({entity:g,screenshots:x})=>n(hy,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(m.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):m.map(g=>n(my,{entity:g},g.sha)))]})]})})});function hy({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=ft(),a=Le(),[o,i]=_(!1),c=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},h=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};X(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=et(e,r),m=ly(u),p=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(Qe,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(de,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(ue,{children:o||a.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(at,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:h,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void 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=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ve,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Xs,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&l(ue,{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 my({entity:e}){const t=Le(),[r,s]=_(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return X(()=>{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:a,children:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Qe,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(de,{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:qi(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(at,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,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 py=Object.freeze(Object.defineProperty({__proto__:null,default:uy,loader:dy,meta:cy},Symbol.toStringTag,{value:"Module"}));function fy({request:e,context:t}){const r=t.dbNotifier||_t;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(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
300
|
-
|
|
301
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{a.close()}catch{}}},d=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
302
|
-
|
|
303
|
-
`))}catch{c()}};r.on("change",d);const h=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
304
|
-
|
|
305
|
-
`))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const gy=Object.freeze(Object.defineProperty({__proto__:null,loader:fy},Symbol.toStringTag,{value:"Module"}));function yy(){return new Response(JSON.stringify({status:"ok",version:Hs,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const xy=Object.freeze(Object.defineProperty({__proto__:null,loader:yy},Symbol.toStringTag,{value:"Module"}));function na(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),c=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
|
|
306
|
-
`).filter(h=>h.trim().startsWith("-")).map(h=>h.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):c&&(o.paths=c[1].split(",").map(h=>h.replace(/['"]/g,"").trim()).filter(Boolean));const d=s.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function zr(e,t=""){const r=[];try{const s=await ye.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await zr(te.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Tn(e){const t=await zr(e),r=[];for(const s of t){const a=te.join(e,s);try{const o=await ye.readFile(a,"utf-8"),{frontmatter:i,body:c}=na(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:c})}catch{}}return r}function Gi(e){const t=te.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Ki(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>bs(e,s,{matchBase:!0}));const r=Gi(t);return r?bs(e,r,{matchBase:!0}):!1}function by(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Gi(e)?[]:t.filter(r=>Ki(r,e))}const vy=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function ra(e){const t=[];async function r(s,a){try{const o=await Ce.readdir(s,{withFileTypes:!0});for(const i of o){const c=B.join(s,i.name),d=a?`${a}/${i.name}`:i.name;i.isDirectory()&&vy.has(i.name)||(i.isDirectory()?await r(c,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const wy="codeyam-rule-state.json",hs=1;function Qi(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return xr.createHash("sha256").update(t).digest("hex")}function Zi(e){return te.join(e,".claude",wy)}async function Xi(e){const t=Zi(e);try{const r=await ye.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==hs?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:hs,rules:{}}):s}catch{return{version:hs,rules:{}}}}async function el(e,t){const r=Zi(e),s=te.dirname(r);await ye.mkdir(s,{recursive:!0}),await ye.writeFile(r,JSON.stringify(t,null,2)+`
|
|
307
|
-
`,"utf-8")}async function sa(e,t){const r=await Xi(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await ye.readFile(a.absolutePath,"utf-8"),i=Qi(o),c=r.rules[a.filePath];c?c.contentHash!==i&&(r.rules[a.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await el(e,r),r}async function vo(e,t,r,s){const a=await Xi(e);if(r){const o=te.join(e,".claude","rules"),i=te.join(o,t),c=await ye.readFile(i,"utf-8"),d=Qi(c);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=d):a.rules[t]={contentHash:d,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await el(e,a)}function aa(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function tl(e,t=""){const r=[],s=await ye.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await tl(te.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function hr(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
308
|
-
`).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 Cy({request:e}){const t=xe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=te.join(t,".claude","rules");if(s==="recent-changes")return Sy(t,a);if(s==="reviewed-status")return Ey(t,a);if(s==="audit")return Ay(t,a);if(s==="source-files")return Py(t);if(s==="rule-coverage")return _y(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?ky(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?jy(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await zr(a),i=[];for(const u of o){const m=te.join(a,u);try{const p=await ye.readFile(m,"utf-8"),f=await ye.stat(m),{frontmatter:y,body:g}=na(p);i.push({filePath:u,content:p,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,m)=>new Date(m.lastModified).getTime()-new Date(u.lastModified).getTime());let c=i.length>0;if(!c)try{await ye.access(te.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await Tn(a),h={};if(d.length>0){const u=await sa(t,d);for(const m of d)h[m.filePath]=aa(u,m.filePath)}return Response.json({memories:i,memoryInitialized:c,reviewedStatus:h})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function Ny(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
|
|
309
|
-
`).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let h=[i];if(i.endsWith("/")&&c==="?"){const u=te.join(e,i);try{h=(await tl(u)).map(p=>i+p)}catch{continue}}for(const u of h){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let p="modified";c==="A"||c==="?"?p="added":c==="D"||d==="D"?p="deleted":(c==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&c==="?"){const y=`${e}/${u}`;try{const g=await ye.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
|
|
310
|
-
new file mode 100644
|
|
311
|
-
--- /dev/null
|
|
312
|
-
+++ b/${u}
|
|
313
|
-
@@ -0,0 +1,${g.split(`
|
|
314
|
-
`).length} @@
|
|
315
|
-
${g.split(`
|
|
316
|
-
`).map(x=>"+"+x).join(`
|
|
317
|
-
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
318
|
-
... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&hr(f)||r.push({filePath:m,changeType:p,diff:f})}}}catch{}return r}async function Sy(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Tn(t),o={};if(a.length>0){const u=await sa(e,a);for(const m of a)o[m.filePath]=aa(u,m.filePath)}const c=(await Ny(e,r)).filter(u=>!o[u.filePath]);c.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:c});const h=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(`
|
|
319
|
-
`).filter(Boolean).slice(0,20);for(const u of h){const[m,p,...f]=u.split("|"),y=f.join("|");if(!m||!p)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${m} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const v of g.split(`
|
|
320
|
-
`).filter(Boolean)){const[b,w]=v.split(" ");if(!w||!w.startsWith(".claude/rules/"))continue;const N=w.replace(".claude/rules/","");let C="modified";if(b==="A"?C="added":b==="D"&&(C="deleted"),o[N])continue;let S="";try{S=r(`git show ${m} --format="" -- "${w}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),S.length>5e3&&(S=S.substring(0,5e3)+`
|
|
321
|
-
... (truncated)`)}catch{S="(diff not available)"}C==="modified"&&hr(S)||x.push({filePath:N,changeType:C,diff:S})}x.length>0&&s.push({commitHash:m.substring(0,8),date:p,message:y,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function ky(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.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(hr(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
|
|
322
|
-
... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=te.join(e,s);try{const x=await ye.readFile(g,"utf-8"),v=`diff --git a/${s} b/${s}
|
|
323
|
-
new file mode 100644
|
|
324
|
-
--- /dev/null
|
|
325
|
-
+++ b/${s}
|
|
326
|
-
@@ -0,0 +1,${x.split(`
|
|
327
|
-
`).length} @@
|
|
328
|
-
${x.split(`
|
|
329
|
-
`).map(b=>"+"+b).join(`
|
|
330
|
-
`)}`;return Response.json({diff:{diff:v.length>5e3?v.substring(0,5e3)+`
|
|
331
|
-
... (truncated)`:v,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const h=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!h)return Response.json({diff:null});const[u,m,...p]=h.split("|"),f=p.join("|");if(!u||!m)return Response.json({diff:null});let y=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?hr(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
|
|
332
|
-
... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:m,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function Ey(e,t){try{const r=await Tn(t),s={};if(r.length>0){const a=await sa(e,r);for(const o of r)s[o.filePath]=aa(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Ay(e,t){try{const r=await Tn(t),s=await ra(e),a=[];for(const o of s){const i=r.filter(c=>Ki(o,c));if(i.length>0){const c=i.reduce((d,h)=>d+h.body.length,0);a.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.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 Py(e){try{const t=await ra(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 _y(e,t){try{const[r,s]=await Promise.all([Tn(t),ra(e)]),a={};for(const o of r)a[o.filePath]=by(o,s).length;return Response.json({coverage:a})}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 jy(e,t){try{const r=await zr(e),s=[];for(const o of r){const i=te.join(e,o);try{const c=await ye.readFile(i,"utf-8"),d=await ye.stat(i),{frontmatter:h,body:u}=na(c);h.paths&&h.paths.some(m=>bs(t,m,{matchBase:!0}))&&s.push({filePath:o,content:c,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}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 My({request:e}){const t=xe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=te.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:c}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await vo(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await vo(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=te.normalize(o);if(d.includes("..")||te.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=te.join(r,d);switch(a){case"create":case"update":return i?(await ye.mkdir(te.dirname(h),{recursive:!0}),await ye.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await ye.unlink(h),console.log(`[API] Memory deleted: ${o}`);const u=te.dirname(h);try{(await ye.readdir(u)).length===0&&u!==r&&await ye.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(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 Ty=Object.freeze(Object.defineProperty({__proto__:null,action:My,loader:Cy},Symbol.toStringTag,{value:"Module"}));async function $y({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await vt()),!r)return V({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return V({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return V({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return V({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return V({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?V({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):V({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Ht(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Ht(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return V({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return V({error:"Unknown queryType"},{status:400})}async function Iy({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 vt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),V({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),V({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),V({status:"resumed"});if(a==="pause")return r.pause(),V({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?V({status:"removed",jobId:i}):V({error:"Job not found in queue"},{status:404}):V({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return V({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?V({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?V({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?V({status:"reordered",jobId:i,direction:c}):V({error:"Could not reorder job (not found or at boundary)"},{status:400})}return V({error:"Unknown action"},{status:400})}const Ry=Object.freeze(Object.defineProperty({__proto__:null,action:Iy,loader:$y},Symbol.toStringTag,{value:"Module"})),Dy=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Ly=Ue(function(){return Le(),n(Dr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Vi,{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})]})]})})}),Oy=Object.freeze(Object.defineProperty({__proto__:null,default:Ly,meta:Dy},Symbol.toStringTag,{value:"Module"})),Fy=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function zy({request:e}){var t,r;try{const s=await Ar();if(!s)return V({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const d=await Re();if(d){const{project:h}=await De(d);a=((r=(t=h.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=xe()||process.cwd(),i=await Pr(o),c=pi(s.projectSlug);return V({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:c,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),V({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Yy(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 By({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let h;if(r)try{h=JSON.parse(r)}catch{return V({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return V({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;c&&(m=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let p;if(d)try{p=JSON.parse(d)}catch{return V({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Ar();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const w=Yy(u[b]);return{...v,startCommand:w}}return v}))}if(!await oi({universalMocks:h,pathsToIgnore:m,webapps:f,memory:p}))return V({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=xe()||process.cwd(),v=await Pr(x);g=a!==void 0&&a!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await lu(x,{...v,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return V({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),V({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function wo(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Co({mock:e,onSave:t,onCancel:r}){const[s,a]=_(e.entityName),[o,i]=_(e.filePath),[c,d]=_(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:c,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Uy(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Wy=Ue(function(){var Te,$e,Ie,Oe,Se;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=Je(),i=Pl(),c=Le(),d=lt(),[h,u]=_(a?"project-metadata":"memory");dt({source:"settings-page"});const[m,p]=_((t==null?void 0:t.universalMocks)||[]),[f,y]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=_((r==null?void 0:r.GROQ_API_KEY)||""),[w,N]=_((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,S]=_((r==null?void 0:r.OPENAI_API_KEY)||""),[A,E]=_(!1),[k,j]=_(!1),[R,M]=_(!1),[I,$]=_(!1),[T,q]=_(!1),[K,H]=_(!1),[U,F]=_(null),[L,P]=_(!1),[O,z]=_({}),[J,ee]=_(((Te=t==null?void 0:t.memory)==null?void 0:Te.conversationReflection)??!0),[Y,D]=_((($e=t==null?void 0:t.memory)==null?void 0:$e.ruleMaintenance)??!0),[W,G]=_(((Ie=t==null?void 0:t.memory)==null?void 0:Ie.promptModel)??"haiku");X(()=>{var ne,he,ke,rt;if(t){p(t.universalMocks||[]);const fe=(t.pathsToIgnore||[]).join(", ");y(fe),x(fe);const ze={};(ne=t.webapps)==null||ne.forEach((Be,It)=>{Be.startCommand&&(ze[It]=wo(Be.startCommand))}),z(ze),ee(((he=t.memory)==null?void 0:he.conversationReflection)??!0),D(((ke=t.memory)==null?void 0:ke.ruleMaintenance)??!0),G(((rt=t.memory)==null?void 0:rt.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),N(r.ANTHROPIC_API_KEY||""),S(r.OPENAI_API_KEY||""))},[t,r]),X(()=>{if(i!=null&&i.success){$(!0);const ne=setTimeout(()=>$(!1),3e3);return()=>clearTimeout(ne)}},[i]),X(()=>{if(c.state==="idle"&&c.data&&!K){console.log("[Settings] Fetcher data:",c.data);const ne=c.data;if(ne.success){console.log("[Settings] Save successful, revalidating..."),$(!0),H(!0),(f!==g||ne.requiresRestart)&&q(!0),d.revalidate();const he=setTimeout(()=>{$(!1),H(!1)},3e3);return()=>clearTimeout(he)}}},[c.state,c.data,K,d,f,g]);const Z=ne=>{ne.preventDefault();const he=new FormData(ne.currentTarget);he.set("universalMocks",JSON.stringify(m)),he.set("startCommands",JSON.stringify(O)),he.set("memorySettings",JSON.stringify({conversationReflection:J,ruleMaintenance:Y,promptModel:W})),console.log("[Settings] Submitting form data:",{universalMocks:he.get("universalMocks"),startCommands:he.get("startCommands"),openAiApiKey:he.get("openAiApiKey")?"***":"(empty)"}),c.submit(he,{method:"post"})},re=ne=>{p([...m,ne]),P(!1)},ge=(ne,he)=>{const ke=[...m];ke[ne]=he,p(ke),F(null)},ve=ne=>{p(m.filter((he,ke)=>ke!==ne))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const Ne=[{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"}],Ee=a?Ne:Ne.filter(ne=>ne.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:c.state==="submitting"?"Saving...":"Save Settings"})]}),(I||T||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mb-4 space-y-3",children:[I&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),T&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),l("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(dn,{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(c.data&&typeof c.data=="object"&&"error"in c.data){const ne=c.data;return typeof ne.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:ne.error}):null}return null})()]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ee.map(ne=>n("li",{children:n("button",{type:"button",onClick:()=>u(ne.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${h===ne.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:ne.label})},ne.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:Z,className:"space-y-6",children:[h==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((ne,he)=>{var ke;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ne.path==="."?"Root":ne.path})]}),ne.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ne.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ne.framework})]}),ne.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[ne.startCommand.command," ",(ke=ne.startCommand.args)==null?void 0:ke.join(" ")]})]})]})},he)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),h==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:ne=>b(ne.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:()=>E(!A),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:A?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:w,onChange:ne=>N(ne.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>j(!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"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:R?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:ne=>S(ne.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:()=>M(!R),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:R?"Hide":"Show"})]})]})]})]})]}),h==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((ne,he)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:ne.path==="."?"Root":ne.path}),n("div",{className:"text-sm text-gray-600",children:ne.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${he}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${he}`,name:`startCommand-${he}`,value:O[he]||"",onChange:ke=>z({...O,[he]:ke.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"})]})]},he))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),h==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:ne=>y(ne.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),h==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),m.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>P(!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:m.map((ne,he)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:U===he?n(Co,{mock:ne,onSave:ke=>ge(he,ke),onCancel:()=>F(null)}):n(ue,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:ne.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:ne.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:ne.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>F(he),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:()=>ve(he),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},he))}),m.length>0&&n("button",{type:"button",onClick:()=>P(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),h==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":J,onClick:()=>ee(!J),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 ${J?"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 ${J?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":Y,onClick:()=>D(!Y),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 ${Y?"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 ${Y?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(ne=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${W===ne.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:ne.value,checked:W===ne.value,onChange:()=>G(ne.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:ne.label}),ne.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:ne.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:ne.description})]})]},ne.value))})]})]})]}),h==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((ne,he)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ne.path==="."?"Root":ne.path})]}),ne.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ne.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ne.framework})]}),ne.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:wo(ne.startCommand)})]})]})},he))})]})]}),s&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&l("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&&l("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||((Oe=s.templateVersion.gitCommit)==null?void 0:Oe.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Uy(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&l("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||((Se=s.cachedAnalyzerVersion.gitCommit)==null?void 0:Se.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)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),L&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Co,{mock:{entityName:"",filePath:"",content:""},onSave:re,onCancel:()=>P(!1)})]})})]})})}),Hy=Object.freeze(Object.defineProperty({__proto__:null,action:By,default:Wy,loader:zy,meta:Fy},Symbol.toStringTag,{value:"Module"}));async function Jy({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=xe();if(!r)return new Response("Project root not found",{status:500});const a=te.extname(t)!==""?t:`${t}.html`,o=te.join(r,".codeyam","captures","static",a);try{await ye.access(o);let i=await ye.readFile(o);const c=te.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],y)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const Vy=Object.freeze(Object.defineProperty({__proto__:null,loader:Jy},Symbol.toStringTag,{value:"Module"}));function qy(e,t,r=10){var d;const s=new Map,a=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)a(h)&&s.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const y of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(y)}}const i=[],c=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),c.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const m=o.get(h);if(m)for(const p of m){if(c.has(p))continue;c.add(p);const f=t.find(y=>y.sha===p);if(f){if(a(f)){const y=u+1,g=s.get(p);(!g||y<g.depth)&&s.set(p,{entity:f,depth:y})}i.push({sha:p,depth:u+1})}}}return Array.from(s.values()).sort((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function mr(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 a=s.sort((o,i)=>{var h,u;const c=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(a[0])}return r}function nl(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(d=>d.filePath===a.path||a.status==="renamed"&&a.oldPath&&d.filePath===a.oldPath),i=o.filter(d=>{var h,u;return s.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=mr(i);r.set(a.path,{status:a,entities:o,editedEntities:c})}return r}function Gy(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),c=mr(i);s.set(o.path,{status:o,entities:c})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const c=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=mr(c);s.set(o.path,{status:o,entities:d})}}return s}function Ky(e,t){const r=new Map,s=rl(e,t);for(const a of s){const i=qy([a],t).filter(({depth:c})=>c>0);r.set(a.sha,i)}return r}function rl(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return mr(s)}function Qy({recentSimulations:e}){const t=ae(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Sn,{size:16,style:{color:"#8B5CF6"}})}),n(de,{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,a)=>n(de,{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:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(Ve,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(de,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Sn,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(de,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(de,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Zy="/assets/codeyam-name-logo-CvKwUgHo.svg",Xy=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function ex({request:e,context:t}){var r,s,a,o,i;try{const c=await Re();if(c){const{project:I}=await De(c);if(((r=I.metadata)==null?void 0:r.editorMode)??!1)return Ma("/editor");if(!(((a=(s=I.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1))return Ma("/memory")}const d=t.analysisQueue,h=d?d.getState():{paused:!1,jobs:[]},[u,m]=await Promise.all([Vt(),on()]),p=Ii(),f=u?nl(p,u):new Map,y=Array.from(f.entries()).sort((I,$)=>I[0].localeCompare($[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter(I=>I.entityType==="visual").length)||0,v=(u==null?void 0:u.filter(I=>I.entityType==="library").length)||0,b=u?rl(p,u):[],w=b.length,N=(u==null?void 0:u.filter(I=>(I.analyses??[]).filter($=>$.scenarios&&$.scenarios.length>0).length>0).length)||0,C=(u==null?void 0:u.reduce((I,$)=>{var q,K,H;const T=((H=(K=(q=$.analyses)==null?void 0:q[0])==null?void 0:K.scenarios)==null?void 0:H.length)||0;return I+T},0))||0,S=(u==null?void 0:u.reduce((I,$)=>{var K,H;const q=(((H=(K=$.analyses)==null?void 0:K[0])==null?void 0:H.scenarios)||[]).filter(U=>{var F,L;return(L=(F=U.metadata)==null?void 0:F.screenshotPaths)==null?void 0:L[0]}).length;return I+q},0))||0,A=[];u==null||u.forEach(I=>{var T;const $=(T=I.analyses)==null?void 0:T[0];$!=null&&$.scenarios&&$.scenarios.filter(K=>{var H;return!((H=K.metadata)!=null&&H.sameAsDefault)}).forEach(K=>{var U,F;const H=(F=(U=K.metadata)==null?void 0:U.screenshotPaths)==null?void 0:F[0];H&&A.push({entitySha:I.sha,entityName:I.name,scenarioId:K.id,scenarioName:K.name,screenshotPath:H,createdAt:$.createdAt||""})})}),A.sort((I,$)=>new Date($.createdAt).getTime()-new Date(I.createdAt).getTime());const E=A.slice(0,16),k=(u==null?void 0:u.filter(I=>I.entityType==="visual").filter(I=>{var q,K;const $=(q=I.analyses)==null?void 0:q[0];return!((K=$==null?void 0:$.scenarios)==null?void 0:K.some(H=>{var U,F;return(F=(U=H.metadata)==null?void 0:U.screenshotPaths)==null?void 0:F[0]}))}).slice(0,8))||[],j=(o=m==null?void 0:m.metadata)==null?void 0:o.currentRun,R=((i=j==null?void 0:j.currentEntityShas)==null?void 0:i.length)||0,M=h.jobs.length||0;return V({stats:{totalEntities:g,visualEntities:x,libraryEntities:v,uncommittedEntities:w,entitiesWithAnalyses:N,totalScenarios:C,capturedScreenshots:S,currentlyAnalyzing:R,filesOnQueue:M},uncommittedFiles:y,uncommittedEntitiesList:b,recentSimulations:E,visualEntitiesForSimulation:k,projectSlug:c,queueState:h,currentCommit:m})}catch(c){return console.error("Failed to load dashboard data:",c),V({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 tx=Ue(function(){var U,F;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=Je(),h=Le(),u=lt(),{showToast:m}=zs();dt({source:"dashboard"});const[p,f]=_(new Set),[y,g]=_(null),[x,v]=_(!1),[b,w]=_(!1),{lastLine:N,isCompleted:C}=yt(i,!!y),{simulatingEntity:S,scenarios:A,scenarioStatuses:E,allScenariosCaptured:k}=ae(()=>{var D,W;const L={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return L;const P=o==null?void 0:o.find(G=>G.sha===y);if(!P)return L;const O=(D=P.analyses)==null?void 0:D[0],z=(O==null?void 0:O.scenarios)||[],J=((W=O==null?void 0:O.status)==null?void 0:W.scenarios)||[],ee=J.filter(G=>G.screenshotFinishedAt).length,Y=z.length>0&&ee===z.length;return{simulatingEntity:P,scenarios:z,scenarioStatuses:J,allScenariosCaptured:Y}},[y,o]);X(()=>{(C||k)&&g(null)},[C,k]);const j=(U=d==null?void 0:d.metadata)==null?void 0:U.currentRun,R=new Set((j==null?void 0:j.currentEntityShas)||[]),M=new Set(c.jobs.flatMap(L=>L.entityShas||[])),I=new Set(((F=c.currentlyExecuting)==null?void 0:F.entityShas)||[]),$=s.filter(L=>L.entityType==="visual"||L.entityType==="library"),T=$.filter(L=>!R.has(L.sha)&&!M.has(L.sha)&&!I.has(L.sha)),q=()=>{if(T.length===0){m("All entities are already queued or analyzing","info",3e3);return}const L=T.map(P=>P.sha);w(!0),m(`Starting analysis for ${T.length} entities...`,"info",3e3),h.submit({entityShas:L.join(",")},{method:"post",action:"/api/analyze"})};X(()=>{if(h.state==="idle"&&h.data){const L=h.data;L.success?(console.log("[Analyze All] Success:",L.message),m(`Analysis started for ${L.entityCount} entities in ${L.fileCount} files. Watch the logs for progress.`,"success",6e3),w(!1)):L.error&&(console.error("[Analyze All] Error:",L.error),m(`Error: ${L.error}`,"error",8e3),w(!1))}},[h.state,h.data,m]);const K=L=>{f(P=>{const O=new Set(P);return O.has(L)?O.delete(L):O.add(L),O})},H=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[n("img",{src:Zy,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"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:H.map((L,P)=>n(de,{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:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:L.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[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 →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${L.color}15`},children:[L.iconType==="folder"&&n(tc,{size:20,style:{color:L.color}}),L.iconType==="check"&&n($s,{size:20,style:{color:L.color}}),L.iconType==="image"&&n(Sn,{size:20,style:{color:L.color}}),L.iconType==="code-xml"&&n(nc,{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 →"})]})]})},P))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),$.length>0&&n("button",{onClick:q,disabled:h.state!=="idle"||b||T.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:h.state!=="idle"||b?"Starting analysis...":T.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([L,P])=>{const O=p.has(L),z=P.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>K(L),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:O?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:L}),l("span",{className:"text-xs text-gray-500",children:[z.length," entit",z.length!==1?"ies":"y"]})]})]})}),O&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:z.length>0?z.map(J=>{const ee=R.has(J.sha),Y=M.has(J.sha)||I.has(J.sha);return l(de,{to:`/entity/${J.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:D=>D.currentTarget.style.borderColor="#005C75",onMouseLeave:D=>D.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:J.entityType==="visual"?"#8B5CF615":J.entityType==="library"?"#6366F1":"#EC4899"},children:[J.entityType==="visual"&&n(Sn,{size:16,style:{color:"#8B5CF6"}}),J.entityType==="library"&&n(jo,{size:16,className:"text-white"}),J.entityType==="other"&&n(rc,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:J.name}),J.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),J.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),J.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),J.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:J.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[ee&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(at,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ee&&Y&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ee&&!Y&&n("button",{onClick:D=>{D.preventDefault(),D.stopPropagation(),m(`Starting analysis for ${J.name}...`,"info",3e3),h.submit({entityShas:J.sha},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:D=>D.currentTarget.style.backgroundColor="#004560",onMouseLeave:D=>D.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},J.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},L)})}):l("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(Qy,{recentSimulations:a}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("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:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Qe,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",S.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:S.filePath})]})]})}),k?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):N?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:N,children:N}),i&&n("button",{onClick:()=>v(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):h.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map((L,P)=>{var W,G,Z;const O=(W=S==null?void 0:S.analyses)==null?void 0:W[0],z=Fr(L,O==null?void 0:O.status,void 0,y||void 0,void 0),J=(Z=(G=L.metadata)==null?void 0:G.screenshotPaths)==null?void 0:Z[0],ee=z.isCaptured,Y=z.status==="capturing"||z.status==="starting",D=z.hasError;return ee?n(de,{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(Ve,{screenshotPath:J,alt:L.name,title:L.name,className:"max-w-full max-h-full object-contain object-center"})},P):D?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:z.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},P):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:`${Y?"Capturing":"Pending"} ${L.name}...`,children:n("span",{className:Y?"animate-pulse":"text-gray-400",children:Y?"⋯":"⏹️"})},P)})})]})]})]}),x&&i&&n(At,{projectSlug:i,onClose:()=>v(!1)})]})})}),nx=Object.freeze(Object.defineProperty({__proto__:null,default:tx,loader:ex,meta:Xy},Symbol.toStringTag,{value:"Module"}));function rx(e){const[t,r]=_(null),[s,a]=_(!1),o=ie(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),a(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),a(!1)}))},[e]);return X(()=>{e&&o()},[e,o]),{results:t,isRunning:s,runTests:o}}function xn({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,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"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-32 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function ms({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=rx(e);if(s&&!r)return l("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(!r)return null;if(r.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(c=>{const d=`${t} > `;return c.fullName.startsWith(d)||c.fullName===t}):r.testCases;if(o.length===0)return null;const i=t?`${t} > `:"";return l("div",{className:"px-2 pt-1 space-y-0.5",children:[o.map(c=>{var h;const d=i&&c.fullName.startsWith(i)?c.fullName.slice(i.length):c.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:d})]}),c.status==="failed"&&((h=c.failureMessages)==null?void 0:h.map((u,m)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:u,children:u.split(`
|
|
333
|
-
`)[0]},m)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Zt({filePath:e,projectRoot:t}){if(!e)return null;const s=`vscode://file/${t?`${t}/${e}`:e}`;return l("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[n("span",{className:"text-[9px] text-gray-500 truncate",children:e}),n("a",{href:s,title:"Open in editor",className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors",children:n("svg",{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"})})})]})}function sx({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,onZoomChange:o,analyzedEntities:i=[],glossaryFunctions:c=[],activeAnalyzedScenarioId:d,onAnalyzedScenarioSelect:h,entityImports:u}){const{appScenarios:m,componentGroups:p}=ae(()=>{const C=[],S=new Map;for(const E of e)if(E.componentName){const k=S.get(E.componentName)||[];k.push(E),S.set(E.componentName,k)}else C.push(E);const A=new Map([...S.entries()].sort(([E],[k])=>E.localeCompare(k)));return{appScenarios:C,componentGroups:A}},[e]),f=ae(()=>{const C=new Set((i||[]).filter(A=>A.entityType==="visual").map(A=>A.name)),S=new Map;for(const[A,E]of p)C.has(A)||S.set(A,E);return S},[p,i]),{visualEntities:y,libraryEntities:g}=ae(()=>{const C=i.filter(A=>A.entityType==="visual").sort((A,E)=>A.name.localeCompare(E.name)),S=i.filter(A=>A.entityType==="library"||A.entityType==="functionCall").sort((A,E)=>A.name.localeCompare(E.name));return{visualEntities:C,libraryEntities:S}},[i]),x=ae(()=>{const C=new Set(g.map(S=>S.name));return c.filter(S=>!C.has(S.name)).sort((S,A)=>S.name.localeCompare(A.name))},[c,g]),v=i.some(C=>C.isAnalyzing),b=be(null),w=be(0),N=ie(()=>{b.current&&(w.current=b.current.scrollTop)},[]);if(X(()=>{b.current&&w.current>0&&(b.current.scrollTop=w.current)}),e.length===0&&i.length===0&&x.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("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(a){const C=p.get(a)||[],S=new Set((u==null?void 0:u[a])||[]),A=S.size>0,E=A?y.filter(j=>S.has(j.name)):[],k=A?g.filter(j=>S.has(j.name)):[];return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-1",children:[l("button",{onClick:()=>o(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})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:C.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):C.map(j=>n(xn,{imgSrc:j.screenshotPath?`/api/editor-scenario-image/${j.id}.png`:null,name:j.name,isActive:j.id===r,onSelect:()=>s(j)},j.id))}),E.length>0&&l("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"})}),E.map(j=>l("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>o(j.name),className:"text-xs font-medium text-gray-300 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:j.name})}),n(Zt,{filePath:j.filePath,projectRoot:t}),(j.scenarios.length>0||j.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:j.scenarios.map(R=>n(xn,{imgSrc:R.screenshotPath?`/api/screenshot/${R.screenshotPath}`:null,name:R.name,isActive:R.id===d,onSelect:()=>h==null?void 0:h({analysisId:j.analysisId,scenarioId:R.id,scenarioName:R.name,entitySha:j.sha,entityName:j.name})},R.id))})]},j.sha))]}),k.length>0&&l("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(j=>l("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(Zt,{filePath:j.filePath,projectRoot:t}),j.testFile&&n(ms,{testFile:j.testFile,entityName:j.name})]},j.sha))]})]})})}return n("div",{ref:b,onScroll:N,className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-3",children:[m.length>0&&l("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Page Scenarios"})}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:m.map(C=>n(xn,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===r&&!d,onSelect:()=>s(C)},C.id))})]}),f.size>0&&l("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"})}),[...f.entries()].map(([C,S])=>{var A;return l("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>o(C),className:"text-xs font-medium text-gray-300 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C})}),((A=S[0])==null?void 0:A.componentPath)&&n(Zt,{filePath:S[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:S.map(E=>n(xn,{imgSrc:E.screenshotPath?`/api/editor-scenario-image/${E.id}.png`:null,name:E.name,isActive:E.id===r&&!d,onSelect:()=>s(E)},E.id))})]},C)})]}),y.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),v&&e.length===0&&i.every(C=>C.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),y.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>o(C.name),className:"text-xs font-medium text-gray-300 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("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(Zt,{filePath:C.filePath,projectRoot:t}),(C.scenarios.length>0||C.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[C.scenarios.map(S=>n(xn,{imgSrc:S.screenshotPath?`/api/screenshot/${S.screenshotPath}`:null,name:S.name,isActive:S.id===d,onSelect:()=>h==null?void 0:h({analysisId:C.analysisId,scenarioId:S.id,scenarioName:S.name,entitySha:C.sha,entityName:C.name})},S.id)),C.pendingScenarios.map(S=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:S,children:S},S))]})]},C.sha))]}),(g.length>0||x.length>0)&&l("div",{className:`pt-2 mt-1 ${y.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"})}),g.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("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(Zt,{filePath:C.filePath,projectRoot:t}),C.testFile?n(ms,{testFile:C.testFile,entityName:C.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},C.sha)),x.map(C=>l("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name})}),n(Zt,{filePath:C.filePath,projectRoot:t}),n(ms,{testFile:C.testFile,entityName:C.name})]},C.name))]})]})})}const ax={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 ox(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function ix(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}function lx({isActive:e}){const[t,r]=_([]),[s,a]=_(!0),[o,i]=_(new Set),c=ie(u=>{i(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})},[]),d=ie(async()=>{try{const u=await fetch("/api/editor-journal");if(u.ok){const m=await u.json();r(m.entries||[])}}catch{}finally{a(!1)}},[]);if(X(()=>{d()},[d]),X(()=>{e&&d()},[e,d]),X(()=>{const u=new EventSource("/api/events");return u.addEventListener("message",m=>{try{const p=JSON.parse(m.data);p.type==="db-change"&&p.changeType==="journal"&&d()}catch{}}),()=>u.close()},[d]),s)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(t.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("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 h=new Map;for(const u of[...t].reverse()){const m=h.get(u.date)||[];m.push(u),h.set(u.date,m)}return n("div",{className:"flex-1 overflow-auto",children:n("div",{className:"p-3 space-y-4",children:[...h.entries()].map(([u,m])=>l("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:ix(u)})}),n("div",{className:"space-y-2",children:m.map((p,f)=>{const y=ax[p.type]||{label:p.type,color:"bg-gray-600"},g=`${p.time}-${f}`,x=o.has(g);return l("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[l("div",{className:`p-3 space-y-2 ${x?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2",children:l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:p.title}),n("span",{className:`${y.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:y.label})]}),n("span",{className:"text-[10px] text-gray-500",children:ox(p.time)})]})}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:p.description}),p.screenshot&&n("div",{className:"rounded overflow-hidden border border-[#3d3d3d] bg-[#1e1e1e] flex items-center justify-center p-1",children:n("img",{src:`/api/editor-journal-image/${p.screenshot.replace("screenshots/","")}`,alt:p.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),p.scenarioScreenshots&&p.scenarioScreenshots.length>0&&(()=>{const v=new Map;for(const w of p.scenarioScreenshots){const N=w.name.indexOf(" - "),C=N!==-1?w.name.slice(0,N):"App",S=v.get(C)||[];S.push(w),v.set(C,S)}const b=[...v.entries()].sort(([w],[N])=>w==="App"?-1:N==="App"?1:w.localeCompare(N));return n("div",{className:"space-y-1.5",children:b.map(([w,N])=>l("div",{children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:w}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:N.map(C=>n("div",{className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] bg-[#1e1e1e] shrink-0 flex items-center justify-center",children:n("img",{src:`/api/editor-journal-image/${C.path.replace("screenshots/","")}`,alt:C.name,title:C.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},C.path))})]},w))})})(),p.commitSha&&l("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:p.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:p.commitMessage})]})]}),l("button",{onClick:()=>c(g),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",x?"Collapse":"Expand"," ———"]})]},g)})})]},u))})})}function St({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-24 h-24 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,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"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-24 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function cx({hasProject:e,scenarios:t,analyzedEntities:r,activeScenarioId:s,onScenarioSelect:a,onAnalyzedScenarioSelect:o,onSwitchToBuild:i,zoomComponent:c,onZoomChange:d,entityImports:h}){const{pageGroups:u,componentGroups:m}=ae(()=>{const v=new Map,b=new Map;for(const N of t)if(N.componentName){const C=b.get(N.componentName)||[];C.push(N),b.set(N.componentName,C)}else{const C="Home",S=v.get(C)||[];S.push(N),v.set(C,S)}const w=new Map([...b.entries()].sort(([N],[C])=>N.localeCompare(C)));return{pageGroups:v,componentGroups:w}},[t]),p=be(null),f=be(0),y=ie(()=>{p.current&&(f.current=p.current.scrollTop)},[]);if(X(()=>{p.current&&f.current>0&&(p.current.scrollTop=f.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Ready to build something?"}),n("button",{onClick:i,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 g=ae(()=>r.filter(v=>v.entityType==="visual").sort((v,b)=>v.name.localeCompare(b.name)),[r]);if(!(t.length>0||g.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed max-w-[280px]",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:i,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(c){const v=u.get(c)||[],b=m.get(c)||[],w=g.find(k=>k.name===c),N=u.has(c),C=new Set((h==null?void 0:h[c])||[]),S=C.size>0,A=S?[...m.entries()].filter(([k])=>C.has(k)):[...m.entries()],E=S?g.filter(k=>C.has(k.name)):g;return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-3",children:[l("button",{onClick:()=>d(void 0),className:"flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0",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"]}),n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:c}),v.length>0&&n("div",{className:"flex flex-wrap gap-2",children:v.map(k=>n(St,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===s,onSelect:()=>a(k)},k.id))}),b.length>0&&n("div",{className:"flex flex-wrap gap-2",children:b.map(k=>n(St,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===s,onSelect:()=>a(k)},k.id))}),w&&(w.scenarios.length>0||w.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2",children:[w.scenarios.map(k=>n(St,{imgSrc:k.screenshotPath?`/api/screenshot/${k.screenshotPath}`:null,name:k.name,isActive:!1,onSelect:()=>o({analysisId:w.analysisId,scenarioId:k.id,scenarioName:k.name,entitySha:w.sha,entityName:w.name})},k.id)),w.pendingScenarios.map(k=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:k,children:k},k))]}),N&&A.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),A.map(([k,j])=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>d(k),className:"text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:j.map(R=>n(St,{imgSrc:R.screenshotPath?`/api/editor-scenario-image/${R.id}.png`:null,name:R.name,isActive:R.id===s,onSelect:()=>a(R)},R.id))})]},k))]}),N&&E.length>0&&l("div",{className:`${A.length===0?"pt-2 mt-1 border-t border-[#3d3d3d]":"mt-2"}`,children:[A.length===0&&n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),E.map(k=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>d(k.name),className:"text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k.name})}),(k.scenarios.length>0||k.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[k.scenarios.map(j=>n(St,{imgSrc:j.screenshotPath?`/api/screenshot/${j.screenshotPath}`:null,name:j.name,isActive:!1,onSelect:()=>o({analysisId:k.analysisId,scenarioId:j.id,scenarioName:j.name,entitySha:k.sha,entityName:k.name})},j.id)),k.pendingScenarios.map(j=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:j,children:j},j))]})]},k.sha))]}),v.length===0&&b.length===0&&!w&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"})]})})}return n("div",{ref:p,onScroll:y,className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-4",children:[n("h2",{className:"text-sm font-medium text-gray-300 m-0 font-['IBM_Plex_Sans']",children:"What do you want to work on next?"}),n("button",{onClick:i,className:"w-full py-3 border-2 border-dashed border-[#4d4d4d] rounded-lg text-sm text-gray-400 hover:border-[#005c75] hover:text-white transition-colors cursor-pointer bg-transparent",children:"+ New Page"}),[...u.entries()].map(([v,b])=>l("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>d(v),className:"text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:v})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:b.map(w=>n(St,{imgSrc:w.screenshotPath?`/api/editor-scenario-image/${w.id}.png`:null,name:w.name,isActive:w.id===s,onSelect:()=>a(w)},w.id))})]},v)),m.size>0&&n("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...m.entries()].map(([v,b])=>l("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>d(v),className:"text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:v})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:b.map(w=>n(St,{imgSrc:w.screenshotPath?`/api/editor-scenario-image/${w.id}.png`:null,name:w.name,isActive:w.id===s,onSelect:()=>a(w)},w.id))})]},v)),g.map(v=>l("div",{children:[l("div",{className:"flex items-center gap-2 py-1",children:[n("button",{onClick:()=>d(v.name),className:"text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:v.name}),v.isAnalyzing&&v.scenarioCount===0&&l("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..."]})]}),(v.scenarios.length>0||v.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[v.scenarios.map(b=>n(St,{imgSrc:b.screenshotPath?`/api/screenshot/${b.screenshotPath}`:null,name:b.name,isActive:!1,onSelect:()=>o({analysisId:v.analysisId,scenarioId:b.id,scenarioName:b.name,entitySha:v.sha,entityName:v.name})},b.id)),v.pendingScenarios.map(b=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:b,children:b},b))]})]},v.sha))]})})}function dx({items:e,onNavigate:t}){return e.length===0?null:n("nav",{className:"flex items-center gap-1 text-xs",children:e.map((r,s)=>{const a=s===e.length-1;return l("span",{className:"flex items-center gap-1",children:[s>0&&n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),a?n("span",{className:"text-white font-medium",children:r.name}):n("button",{onClick:()=>t(r.componentName),className:"text-gray-400 hover:text-white transition-colors cursor-pointer",children:r.name})]},r.componentName||"app")})})}const ux=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function hx({request:e}){var h,u;const t=await Re();let r=!1,s=[];if(t){const{project:m}=await De(t);r=((h=m.metadata)==null?void 0:h.editorMode)??!1;try{const p=Me();for(const b of["component_name","component_path","screenshot_path","url"])try{await p.schema.alterTable("editor_scenarios").addColumn(b,"varchar").execute()}catch{}const f=xe()||process.cwd(),y=B.join(f,".codeyam","editor-step.json");let g=null;try{const b=Q.readFileSync(y,"utf8");g=JSON.parse(b).featureStartedAt||null}catch{}let x=p.selectFrom("editor_scenarios").selectAll().where("project_id","=",m.id);if(g){const b=g.replace("T"," ").replace(/\.\d{3}Z$/,"");x=x.where("created_at",">=",b)}s=(await x.orderBy("created_at","asc").execute()).map(b=>({id:b.id,name:b.name,description:b.description||"",componentName:b.component_name||null,componentPath:b.component_path||null,screenshotPath:b.screenshot_path||null,url:b.url||null}))}catch{}}const a=[...new Set(s.map(m=>m.componentName).filter(m=>m!==null))];let o=[];try{const m=xe()||process.cwd(),p=B.join(m,".codeyam","glossary.json");if(Q.existsSync(p)){const f=Q.readFileSync(p,"utf8");o=JSON.parse(f)}}catch{}const i=o.filter(m=>m.testFile&&m.returnType!=="JSX.Element"&&m.returnType!=="React.ReactNode").map(m=>({name:m.name,filePath:m.filePath,description:m.description||"",testFile:m.testFile,feature:m.feature}));let c=[];try{c=(await Vt()||[]).filter(p=>p.analyses&&p.analyses.length>0).map(p=>{var C;const f=p.analyses[0],y=f.scenarios||[],g=!((C=f.status)!=null&&C.finishedAt),x=p.entityType||"visual",v=x==="library"||x==="functionCall",b=y.filter(S=>{var A,E,k,j,R;return v?!!((A=S.metadata)!=null&&A.executionResult):((k=(E=S.metadata)==null?void 0:E.screenshotPaths)==null?void 0:k[0])&&!((j=S.metadata)!=null&&j.noScreenshotSaved)&&!((R=S.metadata)!=null&&R.sameAsDefault)}),w=y.filter(S=>{var A,E,k,j;return v?!((A=S.metadata)!=null&&A.executionResult):!((k=(E=S.metadata)==null?void 0:E.screenshotPaths)!=null&&k[0])||((j=S.metadata)==null?void 0:j.noScreenshotSaved)}),N=o.find(S=>S.filePath===(p.filePath||""));return{sha:p.sha,name:p.name,entityType:x,filePath:p.filePath||"",analysisId:f.id,isAnalyzing:g,scenarioCount:y.length,scenarios:b.map(S=>{var A,E;return{id:S.id,name:S.name,description:S.description||"",screenshotPath:((E=(A=S.metadata)==null?void 0:A.screenshotPaths)==null?void 0:E[0])||null}}),pendingScenarios:w.map(S=>S.name),testFile:N==null?void 0:N.testFile}})}catch{}const d={};try{if(c.length>0){const m=c.map(f=>f.sha);await We();const p=await ot({shas:m});if(p&&p.length>0){const f=new Set([...c.map(y=>y.name),...a]);for(const y of p){const x=(((u=y.metadata)==null?void 0:u.importedExports)||[]).map(v=>v.name).filter(v=>f.has(v));x.length>0&&(d[y.name]=x)}}}}catch{}return V({projectSlug:t,projectRoot:xe(),hasProject:!!t,editorMode:r,devServerUrl:null,scenarios:s,components:a,analyzedEntities:c,glossaryFunctions:i,entityImports:d})}const ps=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function mx({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:c,isLoading:d}=qt({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return X(()=>{o(i,c||d)},[i,c,d,o]),null}const px=Ue(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,analyzedEntities:o,glossaryFunctions:i,entityImports:c}=Je(),d=lt(),[h,u]=sn(),m=be(null),p=be(null),f=be(null),y=h.get("zoom")||void 0,g=h.get("scenario")||void 0;X(()=>{if(!g)return;const se=a.find(me=>me.id===g);if(!se)return;const le=se.name.replace(/[^a-zA-Z0-9_]+/g,"_");fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:le,scenarioId:se.id})}).catch(()=>{})},[g,a]),X(()=>{const se=new BroadcastChannel("codeyam-editor");return se.onmessage=le=>{var me;if(((me=le.data)==null?void 0:me.type)==="switch-scenario"&&le.data.scenarioId){const we=le.data.scenarioId,He=a.find(hn=>hn.id===we);if(!He)return;const wt=new URLSearchParams(h);wt.set("scenario",we),wt.delete("zoom"),u(wt),I(null),T(null);const Rn=He.name.replace(/[^a-zA-Z0-9_]+/g,"_");fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Rn,scenarioId:we})}).then(()=>{he(hn=>hn+1),k(!1)}).catch(()=>{})}},()=>se.close()},[h,u,a]),X(()=>{if(h.get("ref")!=="link"||!g)return;const se=new BroadcastChannel("codeyam-editor");se.postMessage({type:"switch-scenario",scenarioId:g}),se.close(),window.close()},[]);const[x,v]=_(null),[b,w]=_(null),[N,C]=_(!1),[S,A]=_(null),[E,k]=_(!1),[j,R]=_(!0),[M,I]=_(null),[$,T]=_(null),[q,K]=_(!1),H=ie((se,le)=>{T(me=>(se&&se!==me&&k(!1),se)),!le&&se&&k(!0),K(le)},[]),U=ie(se=>{I(me=>(me&&me.analysisId===se.analysisId||(T(null),he(He=>He+1)),se)),K(!0),k(!1);const le=new URLSearchParams(h);le.delete("scenario"),le.delete("zoom"),u(le)},[h,u]),[F,L]=_(1440),[P,O]=_({name:"Desktop",width:1440,height:900}),[z,J]=_(!1),[ee,Y]=_(null),[D,W]=_("app"),G=ie(()=>{W("build"),re(!0)},[]),[Z,re]=_(!1),[ge,ve]=_(!1),Ne=ie(se=>{ve(se)},[]),[Ee,Te]=_(!1),$e=ie(()=>{if(Ee){Te(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(se=>{se==="granted"&&Te(!0)}):Te(!0)},[Ee]);X(()=>{if(D==="build"){ve(!1);const se=setTimeout(()=>{var le,me;(le=m.current)==null||le.scrollToBottom(),(me=m.current)==null||me.focus()},50);return()=>clearTimeout(se)}},[D]);const[Ie,Oe]=_(null);X(()=>{const se=f.current;if(!se)return;const le=new ResizeObserver(me=>{const we=me[0];we&&Oe({width:we.contentRect.width,height:we.contentRect.height})});return le.observe(se),()=>le.disconnect()},[]);const Se=ae(()=>{if(!Ie)return 1;const se=P.width,le=P.height??900,me=Ie.width,we=Ie.height;return se<=me&&le<=we?1:Math.min(me/se,we/le)},[Ie,P]),[ne,he]=_(0),ke=ie(()=>{he(se=>se+1)},[]),{customSizes:rt,addCustomSize:fe}=Rr(t),ze=ae(()=>[...ps,...rt],[rt]),Be=be(!1);X(()=>{let se=!1,le=null;const me=async()=>{try{const we=await fetch("/api/editor-dev-server");if(se)return;const He=await we.json();if(He.status==="error")v(null),w(null),C(!1),A(He.errorMessage||"Dev server crashed");else if(He.url)v(He.url),w(He.proxyUrl||null),C(!1),A(null),R(!0);else if(He.status==="starting")C(!0),A(null),R(!0);else if(He.status==="stopped")if(x)v(null),C(!1);else if(Be.current)C(!1);else{Be.current=!0;try{(await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})})).ok?C(!0):R(!1)}catch{}}}catch{}};return me(),le=setInterval(()=>void me(),2e3),()=>{se=!0,le&&clearInterval(le)}},[x]),X(()=>{const se=new EventSource("/api/events");let le=null;return se.addEventListener("message",me=>{try{const we=JSON.parse(me.data);(we.type==="db-change"||we.type==="unknown")&&(le&&clearTimeout(le),le=setTimeout(()=>{d.revalidate()},2e3))}catch{}}),()=>{le&&clearTimeout(le),se.close()}},[d]);const It=ae(()=>{const se=[{name:"App"}];return y&&se.push({name:y,componentName:y}),se},[y]),$n=ie(se=>{const le=new URLSearchParams(h);if(se){le.set("zoom",se);const me=a.find(we=>we.componentName===se||we.componentName===null&&se==="Home");if(me){le.set("scenario",me.id);const we=me.name.replace(/[^a-zA-Z0-9_]+/g,"_");fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:we,scenarioId:me.id})}).catch(()=>{}),he(He=>He+1),k(!1)}else le.delete("scenario")}else le.delete("zoom"),le.delete("scenario");u(le)},[h,u,a]),Br=ie(se=>{I(null),T(null);const le=new URLSearchParams(h);le.set("scenario",se.id),u(le);const me=se.name.replace(/[^a-zA-Z0-9_]+/g,"_");fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:me,scenarioId:se.id})}).catch(()=>{}),he(we=>we+1),k(!1)},[h,u]),da=(se,le)=>{L(se);const me=ze.find(we=>we.width===se&&we.height===le);O({name:(me==null?void 0:me.name)||"Custom",width:se,height:le})},Rt=se=>{L(se.width),O({name:se.name,width:se.width,height:se.height})},Dt=se=>{fe(se,P.width,P.height??900),J(!1),O(le=>({...le,name:se}))},In=()=>{M||k(!0)},un=ie(()=>{A(null),C(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),Ur=ie(()=>{A(null),C(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]),Gt=ae(()=>{if(M&&$)return $;if(g){const le=a.find(me=>me.id===g);if(le!=null&&le.url){const me=b||x;return me?le.url.startsWith("/")?`${me}${le.url}`:le.url:null}}const se=b||x;if(!se)return null;if(y&&g){const le=a.find(we=>we.id===g),me=le?le.name.replace(/[^a-zA-Z0-9_]+/g,"_"):"Default";return`${se}/__codeyam__/${y}/${me}`}return se},[b,x,y,g,a,M,$]);return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[M&&n(mx,{analysisId:M.analysisId,scenarioId:M.scenarioId,scenarioName:M.scenarioName,entityName:M.entityName,projectSlug:t,onStateChange:H},M.analysisId),n("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Cr,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:"Editor"}),y&&l(ue,{children:[n("div",{className:"w-px h-4 bg-gray-600"}),n(dx,{items:It,onNavigate:$n})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-auto",children:"Code + Data"})]})}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ps[ps.length-1].width}px`,width:"100%"},children:n($r,{currentViewportWidth:F,currentPresetName:P.name,onDevicePresetClick:Rt,devicePresets:ze,hideLabel:!0,onHoverChange:Y,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(ee==null?void 0:ee.name)||P.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:P.name,onChange:se=>{const le=ze.find(me=>me.name===se.target.value);le&&Rt(le)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[ze.map(se=>n("option",{value:se.name,children:se.name},se.name)),P.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:P.width,onChange:se=>{const le=parseInt(se.target.value,10);!isNaN(le)&&le>0&&da(le,P.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"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:P.height??900}),P.name==="Custom"&&n("button",{onClick:()=>J(!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:f,className:"flex-1 flex items-center justify-center overflow-hidden p-8",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:Gt?n("div",{style:{width:`${P.width*Se}px`,height:`${(P.height??900)*Se}px`},children:l("div",{className:"relative bg-white origin-top-left",style:{width:`${P.width}px`,height:`${P.height??900}px`,transform:Se<1?`scale(${Se})`:void 0},children:[!E&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),n("iframe",{ref:p,src:Gt,className:"w-full h-full border-none",title:"Editor preview",onLoad:In,style:{opacity:E?1:0}},ne)]})}):n("div",{className:"bg-white rounded-lg shadow-sm flex flex-col items-center justify-center",style:{width:`${P.width*Se}px`,height:`${(P.height??900)*Se}px`},children:S?l("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-600 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-gray-100 text-gray-800 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:S}),n("button",{onClick:un,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"})]}):N||q?l(ue,{children:[n("div",{className:"mb-4",children:n(jt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:q?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:q?"Loading component preview...":"Your dev server is starting up..."})]})]}):l("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Code + Data Editor"}),n("p",{className:"text-sm text-[#888] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the chat"})]})})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-r border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden order-first",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>W("app"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${D==="app"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["App",D==="app"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>{W("build"),re(!0)},className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${D==="build"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Build",ge&&D!=="build"&&n("span",{className:"ml-1.5 inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),D==="build"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>W("data"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${D==="data"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Data",D==="data"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>W("journal"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${D==="journal"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Journal",D==="journal"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),typeof Notification<"u"&&n("button",{onClick:$e,className:`px-2 py-1 text-[10px] rounded transition-colors cursor-pointer ${Ee?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:Ee?"Click to turn off notifications":"Click to get notified when Claude finishes",children:Ee?"Notifications On":"Notifications Off"})]}),l("div",{className:"flex-1 overflow-hidden relative",children:[Z&&n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:D==="build"?"visible":"hidden"},children:n(xi,{ref:m,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:ke,editorMode:!0,onIdleChange:Ne,notificationsEnabled:Ee})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:D==="app"?"visible":"hidden"},children:n(cx,{hasProject:s,scenarios:a,analyzedEntities:[],activeScenarioId:g,onScenarioSelect:Br,onAnalyzedScenarioSelect:U,onSwitchToBuild:G,zoomComponent:y,onZoomChange:$n,entityImports:c})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:D==="data"?"visible":"hidden"},children:n(sx,{scenarios:a,projectRoot:r,activeScenarioId:g,onScenarioSelect:Br,zoomComponent:y,onZoomChange:$n,analyzedEntities:[],glossaryFunctions:i,activeAnalyzedScenarioId:M==null?void 0:M.scenarioId,onAnalyzedScenarioSelect:U,entityImports:c})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:D==="journal"?"visible":"hidden"},children:n(lx,{isActive:D==="journal"})})]})]})]}),n(yi,{serverUrl:x,isStarting:N,projectSlug:t,devServerError:S,onStartServer:j?Ur:void 0}),z&&n(Ir,{width:P.width,height:P.height??900,onSave:Dt,onCancel:()=>J(!1)})]})}),fx=Object.freeze(Object.defineProperty({__proto__:null,default:px,loader:hx,meta:ux},Symbol.toStringTag,{value:"Module"}));function sl({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Rc,{remarkPlugins:[Dc],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:a})=>(a==null?void 0:a.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(ue,{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:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function al(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function ol(e){let t=e.memories.length;for(const r of e.children.values())t+=ol(r);return t}function Yr(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 Nn(e){return Math.round(e/3.5)}function Xt(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),h=Math.floor(d/(1e3*60)),u=Math.floor(d/(1e3*60*60));return h<3?"Just now":h<60?`${h}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${a} ${o}`:`${a} ${o}, ${i}`}function gx({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:h,isFadingOut:u,showLeftBorder:m}){const[p,f]=_(!1),[y,g]=_(!1),x=ae(()=>Yr(e.body,e.filePath),[e.body,e.filePath]),v=Nn(e.body.length),b=p?"#3e3e3e":c?"#d97706":"#c7c7c7",w=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,N={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:w,style:N,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!p),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(ue,{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&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:Xt(d)}),o&&n("button",{onClick:C=>{C.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&h&&l("button",{onClick:C=>{C.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(nr,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:C=>{C.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(sc,{className:"w-3 h-3"}),"Edit"]}),l("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(ac,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&h&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.split(`
|
|
339
|
-
`).map((C,S)=>{let A="";return C.startsWith("+")&&!C.startsWith("+++")?A="text-green-400":C.startsWith("-")&&!C.startsWith("---")?A="text-red-400":C.startsWith("@@")&&(A="text-cyan-400"),n("div",{className:A,children:C},S)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(dn,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((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(sl,{content:e.body})})]})]})}function yx(){return new Date().toISOString().split(".")[0]+"",`---
|
|
340
|
-
paths:
|
|
341
|
-
- '**/*.ts'
|
|
342
|
-
---
|
|
343
|
-
|
|
344
|
-
## Title
|
|
345
|
-
|
|
346
|
-
Description here.
|
|
347
|
-
`}function xx({rule:e,onSave:t,onCancel:r}){const[s,a]=_(e?`.claude/rules/${e.filePath}`:""),[o,i]=_((e==null?void 0:e.content)||yx()),[c,d]=_(!!e),[h,u]=_(!1),m=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(_n,{className:"w-5 h-5"})})]}),m&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(nr,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),l("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"),u(!0),setTimeout(()=>u(!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:h?n(ct,{className:"w-4 h-4 text-green-500"}):n(pt,{className:"w-4 h-4"})})]})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!m)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:p=>a(p.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(pt,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${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(pt,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:p=>i(p.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function bx({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ae(()=>al(e),[e]),i=(h,u,m)=>{if(h.target.closest(".chevron-toggle")){m&&a(u||"root");return}const f=u||null;r(t===f?null:f),m&&!s.has(u||"root")&&a(u||"root")},c=h=>{r(t===h?null:h)},d=(h,u=0)=>{const m=s.has(h.path||"root"),p=ol(h),f=h.children.size>0,y=h.name==="root"?"(root)":h.name,g=h.memories.length>0||f,x=h.path||"",v=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,h.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),a(h.path||"root")},children:n(Mt,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(To,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),m&&l("div",{className:"relative",children:[(h.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(b=>{var N;const w=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${w?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(b.filePath),children:n("span",{className:"text-xs",children:(N=b.filePath.split("/").pop())==null?void 0:N.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(h.children.values()).sort((b,w)=>b.name.localeCompare(w.name)).map(b=>d(b,u+1))})]})]},h.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function vx({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[h,u]=_({});X(()=>{u({})},[o]);const m=ae(()=>({...o,...h}),[o,h]),p=ae(()=>al(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?c(g):i(g,x)},y=(g,x=0)=>{const v=s.has(g.path||"root"),b=g.children.size>0,w=g.name==="root"?"root":g.name,N=g.memories.length>0||b;return l("div",{children:[l("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>N&&a(g.path||"root"),children:[N&&n(Mt,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!N&&n("div",{className:"w-4"}),n(To,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:w})]}),v&&l("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(C=>n(gx,{rule:C,onEdit:t,onDelete:r,onView:d,isReviewed:m[C.filePath]??!1,onToggleReviewed:f},C.filePath))}),b&&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(p)})}function wx({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=_("unreviewed"),[i,c]=_("by-date"),[d,h]=_(null),[u,m]=_(!0),[p,f]=_(new Map),y=be(t),g=be([]);X(()=>()=>{g.current.forEach(clearTimeout)},[]),X(()=>{(async()=>{m(!0);try{const S=await(await fetch("/api/memory?action=rule-coverage")).json();h(S.coverage??null)}catch{h(null)}finally{m(!1)}})()},[s]),X(()=>{const N=y.current,C=[];for(const[S,A]of Object.entries(t))A&&!N[S]&&C.push(S);y.current=t,C.length!==0&&(f(S=>{const A=new Map(S);return C.forEach(E=>A.set(E,"approved")),A}),g.current.push(setTimeout(()=>{f(S=>{const A=new Map(S);return C.forEach(E=>A.set(E,"fading")),A})},1500)),g.current.push(setTimeout(()=>{f(S=>{const A=new Map(S);return C.forEach(E=>A.delete(E)),A})},2500)))},[t]);const x=ae(()=>{const N=[...e];return i==="by-impact"&&d!==null?N.sort((C,S)=>{const A=d[C.filePath]??0,E=d[S.filePath]??0;return E!==A?E-A:new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()}):N.sort((C,S)=>new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()),N},[e,i,d]),v=ae(()=>x.filter(N=>!t[N.filePath]).length,[x,t]),b=ae(()=>a==="unreviewed"?x.filter(N=>!t[N.filePath]||p.has(N.filePath)):x,[x,a,t,p]),w=!u&&d!==null;return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),l("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"}),l("button",{onClick:()=>w&&c("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 ${w?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(nt,{className:"w-3 h-3"})]}),l("button",{onClick:()=>c("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(nt,{className:"w-3 h-3"})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n(gs,{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:b.map(N=>{const C=t[N.filePath]??!1,S=p.get(N.filePath),A=Yr(N.body,N.filePath),E=(d==null?void 0:d[N.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:l("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(N),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:A})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:E>0?"text-gray-700 font-medium":"text-gray-300",children:E}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:Xt(N.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"})})})})]})},N.filePath)})}),b.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function Cx(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
348
|
-
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
349
|
-
|
|
350
|
-
${r}
|
|
351
|
-
|
|
352
|
-
Please review these rules in conjunction with one another as they all apply to this file.
|
|
353
|
-
|
|
354
|
-
Review each rule with the other rules in mind:
|
|
355
|
-
- Efficiency: Are the rules concise and well-structured?
|
|
356
|
-
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
357
|
-
- Context window impact: Can the rules be shortened without losing important information?
|
|
358
|
-
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
359
|
-
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
360
|
-
|
|
361
|
-
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 Nx({filePath:e,rulePaths:t,onClose:r}){const[s,a]=_(!1),o=Cx(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:c=>c.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(_n,{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:o,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(o),a(!0),setTimeout(()=>a(!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?l(ue,{children:[n(ct,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function Sx({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=_("unreviewed"),[i,c]=_(null),[d,h]=_(""),[u,m]=_(0),[p,f]=_(!1),[y,g]=_(null),[x,v]=_(null),b=be(null),w=be(null),[N,C]=_({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[S,A]=_(!0);X(()=>{(async()=>{A(!0);try{const K=await(await fetch("/api/memory?action=audit")).json();C({topPaths:K.topPaths||[],totalFilesWithCoverage:K.totalFilesWithCoverage||0,allSourceFiles:K.allSourceFiles||[]})}catch(q){console.error("Failed to load audit data:",q)}finally{A(!1)}})()},[e]);const E=ae(()=>a==="all"?N.topPaths:N.topPaths.filter(T=>T.matchingRules.some(q=>!t[q.filePath])),[N.topPaths,a,t]);ae(()=>N.topPaths.filter(T=>T.matchingRules.some(q=>!t[q.filePath])).length,[N.topPaths,t]);const k=T=>T.split("/").pop()||T,j=ae(()=>{const T=new Map;for(const q of N.topPaths)T.set(q.filePath,q);return T},[N.topPaths]),R=ae(()=>{if(!d.trim())return[];const T=d.toLowerCase(),q=[],K=[];for(const H of N.allSourceFiles){const U=H.toLowerCase();if(!U.includes(T))continue;const F=j.get(H)||{filePath:H,matchingRules:[],totalTextLength:0};U.startsWith(T)?q.push(F):K.push(F)}return q.sort((H,U)=>H.filePath.localeCompare(U.filePath)),K.sort((H,U)=>H.filePath.localeCompare(U.filePath)),[...q,...K].slice(0,8)},[d,N.allSourceFiles,j]),M=ie(T=>{var q;g(T),c(T.filePath),h(T.filePath),f(!1),(q=b.current)==null||q.blur()},[]),I=ie(()=>{var T;h(""),g(null),c(null),(T=b.current)==null||T.focus()},[]),$=ie(T=>{var q;!p||R.length===0||(T.key==="ArrowDown"?(T.preventDefault(),m(K=>Math.min(K+1,R.length-1))):T.key==="ArrowUp"?(T.preventDefault(),m(K=>Math.max(K-1,0))):T.key==="Enter"?(T.preventDefault(),M(R[u])):T.key==="Escape"&&(f(!1),(q=b.current)==null||q.blur()))},[p,R,u,M]);return X(()=>{m(0)},[R]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(Pn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:d,onChange:T=>{h(T.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:$,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:T=>{T.preventDefault(),I()},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"})})}),p&&R.length>0&&n("div",{ref:w,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:R.map((T,q)=>l("div",{onMouseDown:K=>{K.preventDefault(),M(T)},onMouseEnter:()=>m(q),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${q===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(rr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:T.filePath,children:(()=>{const K=T.filePath.toLowerCase().indexOf(d.toLowerCase());if(K===-1)return T.filePath;const H=T.filePath.slice(0,K),U=T.filePath.slice(K,K+d.length),F=T.filePath.slice(K+d.length);return l(ue,{children:[H,n("span",{className:"font-semibold text-[#005C75]",children:U}),F]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[T.matchingRules.length," rule",T.matchingRules.length!==1?"s":""]})]},T.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n(gs,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n(gs,{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:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!S&&(E.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...E.filter(q=>q.filePath!==y.filePath)].slice(0,8):E.slice(0,8)).map((T,q)=>{const K=T.matchingRules.length,H=T.matchingRules.filter(z=>!t[z.filePath]),U=H.length,F=H.reduce((z,J)=>z+J.bodyLength,0),L=U>0,P=i===T.filePath,O=(y==null?void 0:y.filePath)===T.filePath;return l("div",{children:[l("div",{onClick:()=>c(P?null:T.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${O?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[P?n(nt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Mt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(rr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:T.filePath,children:O?T.filePath:k(T.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:U}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:K})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:Nn(F).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Nn(T.totalTextLength).toLocaleString()})]})]}),P&&l("div",{className:"bg-gray-50 border-b border-gray-100",children:[T.matchingRules.map(z=>{const J=r.find(Y=>Y.filePath===z.filePath),ee=t[z.filePath]??!1;return l("div",{onClick:Y=>{Y.stopPropagation(),J&&s(J)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(tr,{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:J?Yr(J.body,J.filePath):z.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Nn(z.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${ee?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:ee&&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"})})})]},z.filePath)}),l("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:z=>{z.stopPropagation(),v({filePath:T.filePath,rulePaths:T.matchingRules.map(J=>J.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},T.filePath)})}),!S&&E.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(Nx,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function kx({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const c=Yr(e.body,e.filePath),d=Nn(e.body.length),h=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[m,p]=_(null),f=(t==null?void 0:t.changeType)==="added"||m!=null&&m.commitCount!=null&&m.commitCount<=1&&!(m.commitCount===1&&m.isUncommitted);return X(()=>{p(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&p(y.diff)}).catch(()=>{})},[e.filePath]),X(()=>{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:l("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:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(ue,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:Xt(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),h&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:h})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(dn,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick: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(ct,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(_n,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),v=x.pop()||y,b=x.length>0?x.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(rr,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:v})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:l("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?Xt(t.date):m!=null&&m.date?Xt(m.date):"recently"]})}):m&&n("div",{className:"px-6 pb-4",children:l("details",{children:[l("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",m.commitMessage," —"," ",Xt(m.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:m.diff.split(`
|
|
362
|
-
`).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)})})]})}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(sl,{content:e.body})})]})]})})}function Ex(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function Ax(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function Px(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(No,{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."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),l("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."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(No,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function No({value:e}){const[t,r]=_(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(ct,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function Gn({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function _x({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(Ex,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(Pn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Is,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(Gn,{label:"Total Rules",count:a.total,icon:n(Ax,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Gn,{label:"Unreviewed",count:a.unreviewed,icon:n(oc,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Gn,{label:"Reviewed",count:a.reviewed,icon:n(ct,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Gn,{label:"Stale",count:a.stale,icon:n(Mo,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function jx({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(_n,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Is,{className:"w-4 h-4"}),"New Rule"]})})]})})}function Mx({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const So="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 rules 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. If you have any questions please ask!",ko="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Eo({text:e}){const[t,r]=_(!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?l(ue,{children:[n(ct,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function Tx({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative 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(_n,{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:So,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(Eo,{text:So})}),l("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:ko,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(Eo,{text:ko})})]})]})})}function $x(){const[e,t]=_(!1);return l(ue,{children:[l("div",{className:"border border-gray-200 rounded-lg px-5 py-4 mb-8 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(Tx,{onClose:()=>t(!1)})]})}const Ix=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function Rx({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?V({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?V({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):V({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),V({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Dx=Ue(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=Je(),o=Le(),i=lt(),[c,d]=_(""),[h,u]=_(null),[m,p]=_(new Set(["root"])),[f,y]=_(null),[g,x]=_(!1),[v,b]=_(null),[w,N]=_(0),[C,S]=_(!1),[A,E]=_(null),[k,j]=_(null),[R,M]=_({}),I=Y=>{p(D=>{const W=new Set(D);return W.has(Y)?W.delete(Y):W.add(Y),W})};dt({source:"memory-page"});const $=ae(()=>({...r,...R}),[r,R]),T=be(o.state);X(()=>{const Y=T.current==="loading"||T.current==="submitting",D=o.state==="idle";Y&&D&&o.data&&(i.revalidate(),y(null),x(!1),N(W=>W+1)),T.current=o.state},[o.state,o.data,i]),X(()=>{M(Y=>{const D={};for(const[W,G]of Object.entries(Y))r[W]!==G&&(D[W]=G);return Object.keys(D).length===Object.keys(Y).length?Y:D})},[r]);const q=(Y,D)=>{M(W=>({...W,[Y]:!0})),o.submit({action:"mark-reviewed",filePath:Y,lastModified:D},{method:"POST",action:"/api/memory",encType:"application/json"})},K=Y=>{M(D=>({...D,[Y]:!1})),o.submit({action:"mark-unreviewed",filePath:Y},{method:"POST",action:"/api/memory",encType:"application/json"})},H=(Y,D)=>{E(Y),j(D??null)},U=ae(()=>{let Y=t;if(c.trim()){const D=c.toLowerCase();Y=Y.filter(W=>{var Z;return(((Z=W.filePath.split("/").pop())==null?void 0:Z.replace(".md",""))||"").toLowerCase().includes(D)||W.body.toLowerCase().includes(D)})}return Y},[t,c]),F=ae(()=>h?U.some(D=>D.filePath===h)?U.filter(D=>D.filePath===h):U.filter(D=>D.filePath.startsWith(h+"/")||D.filePath===h):U,[U,h]),L=(Y,D)=>{const W=f?"update":"create";o.submit({action:W,filePath:Y,content:D},{method:"POST",action:"/api/memory",encType:"application/json"})},P=Y=>{o.submit({action:"delete",filePath:Y.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},O=ae(()=>{const Y=t.filter(D=>$[D.filePath]).length;return{total:t.length,reviewed:Y,unreviewed:t.length-Y,stale:0}},[t,$]),z=ae(()=>{const Y=new Set(["root"]);for(const D of U){const W=D.filePath.split("/");W.pop();let G="";for(const Z of W)G=G?`${G}/${Z}`:Z,Y.add(G)}return Y},[U]),J=z.size===m.size&&[...z].every(Y=>m.has(Y)),ee=()=>{p(J?new Set(["root"]):new Set(z))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(_x,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>S(!0),reviewCounts:O}),(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:Y=>Y.stopPropagation(),children:n(xx,{rule:f,onSave:L,onCancel:()=>{x(!1),y(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(wx,{memories:U,reviewedStatus:$,onViewRule:H,refreshKey:w}),n(Sx,{onEditRule:y,onDeleteRule:b,refreshKey:w,reviewedStatus:$,onMarkReviewed:q,onMarkUnreviewed:K,memories:t,onViewRule:H})]}),n($x,{}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:z.size>1&&n("button",{onClick:ee,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:J?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(bx,{memories:U,selectedPath:h,onSelectPath:u,expandedFolders:m,onToggleFolder:I})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(ic,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),l("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Is,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[h&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:h||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(vx,{memories:F,onEdit:y,onDelete:b,expandedFolders:m,onToggleFolder:I,reviewedStatus:$,onMarkReviewed:q,onMarkUnreviewed:K,onViewRule:H})]})})]}),n("div",{className:"mt-8 mb-8",children:n(de,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),A&&!f&&(()=>{const Y=t.find(D=>D.filePath===A.filePath)??A;return n(kx,{rule:Y,changeInfo:k??void 0,isReviewed:$[Y.filePath]??!1,onApprove:()=>{$[Y.filePath]??!1?K(Y.filePath):q(Y.filePath,Y.lastModified),E(null)},onEdit:()=>{y(Y)},onDelete:()=>{b(Y),E(null)},onClose:()=>E(null)})})(),C&&n(jx,{onClose:()=>S(!1),onCreateNew:()=>{S(!1),x(!0)}}),v&&n(Mx,{rule:v,onConfirm:P,onCancel:()=>b(null)})]})}):n(Px,{})}),Lx=Object.freeze(Object.defineProperty({__proto__:null,default:Dx,loader:Rx,meta:Ix},Symbol.toStringTag,{value:"Module"}));function fs(e){return`${e.filePath||""}::${e.name}`}function il(e,t){const r=Le(),{showToast:s}=zs(),[a,o]=_(new Map);X(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&s(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,s]),X(()=>{var f;if(a.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((v,b)=>{v===x&&p.add(b)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&p.add(x)})}),p.size>0&&o(y=>{const g=new Map(y);return p.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=ie(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=fs(p);o(g=>new Map(g).set(f,p.sha));const y=new FormData;y.append("entitySha",p.sha),y.append("filePath",p.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=ie(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(fs(b),b.sha)),v});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=ie(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=ie(p=>{const f=fs(p);return a.has(f)},[a]),u=ie(p=>{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(p)}))??!1},[t]),m=ae(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function oa({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,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:a?o:"Analyze all entities",children:o})})]})]})]})})}function Ox({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 o=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:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.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 ia({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Yo,{filePath:e}),s&&n(Ox,{status:typeof s=="string"?s:s.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:qi(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function la({entities:e,maxPreviews:t=3}){var s,a,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const h=((a=(s=d.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);m&&r.push({type:"screenshot",screenshot:m,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(de,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(Ve,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(er,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(Ji,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function ca({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,m;const a=t||r?[{entityShas:[e.sha]}]:[],o=et(e,a,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,y;return(y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(de,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Qe,{type:"type"})})}):n(Qe,{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(Zs,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.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"}):c&&n("button",{onClick:p=>{p.preventDefault(),p.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"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((p,f)=>{var g,x;const y=(x=(g=p.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(de,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:v=>v.stopPropagation(),children:n(Ve,{screenshotPath:y,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function Fx({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=sn(),[b,w]=_(new Set),[N,C]=_(""),[S,A]=_(!1),[E,k]=_("all"),[j,R]=_("desc"),M=o||"all",I=ae(()=>{let P=e;return M!=="all"&&(P=P.filter(O=>O.entityType===M)),a==="analyzed"&&(P=P.filter(O=>O.analyses&&O.analyses.length>0)),P},[e,M,a]),$=ae(()=>{const P=new Map,O=new Map,z=new Map;I.forEach(D=>{var Z,re;const W=`${D.filePath}::${D.name}`,G=O.get(W);if(!G)O.set(W,D),z.set(W,[]);else{const ge=((Z=G.metadata)==null?void 0:Z.editedAt)||G.createdAt||"",ve=((re=D.metadata)==null?void 0:re.editedAt)||D.createdAt||"";let Ne=!1;if(ve>ge)Ne=!0;else if(ve===ge){const Ee=G.createdAt||"";Ne=(D.createdAt||"")>Ee}Ne?(z.get(W).push(G),O.set(W,D)):z.get(W).push(D)}}),O.forEach((D,W)=>{var Z;if(!(D.analyses&&D.analyses.length>0)&&((Z=D.metadata)!=null&&Z.previousVersionWithAnalyses)){const ge=(z.get(W)||[]).find(ve=>{var Ne;return ve.sha===((Ne=D.metadata)==null?void 0:Ne.previousVersionWithAnalyses)});ge&&ge.analyses&&ge.analyses.length>0&&(D.analyses=ge.analyses)}}),Array.from(O.values()).sort((D,W)=>{var re,ge,ve,Ne;const G=!((re=D.metadata)!=null&&re.notExported)&&!((ge=D.metadata)!=null&&ge.namedExport),Z=!((ve=W.metadata)!=null&&ve.notExported)&&!((Ne=W.metadata)!=null&&Ne.namedExport);return G&&!Z?-1:!G&&Z?1:0}).forEach(D=>{var ge,ve,Ne,Ee,Te;const W=D.filePath??"No File Path";P.has(W)||P.set(W,{filePath:W,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=P.get(W);G.entities.push(D),G.totalCount++,(ge=D.metadata)!=null&&ge.isUncommitted&&G.uncommittedCount++;const Z=((Ee=(Ne=(ve=D.analyses)==null?void 0:ve[0])==null?void 0:Ne.scenarios)==null?void 0:Ee.length)||0;G.simulationCount+=Z;const re=((Te=D.metadata)==null?void 0:Te.editedAt)||D.updatedAt;re&&(!G.lastUpdated||new Date(re)>new Date(G.lastUpdated))&&(G.lastUpdated=re)});const J=(i==null?void 0:i.jobs)||[],ee=D=>{const W=`${D.filePath||""}::${D.name}`;return(d==null?void 0:d.includes(W))||!1};P.forEach(D=>{const W=D.entities.map(G=>ee(G)?"queued":et(G,J));W.includes("analyzing")||W.includes("queued")?D.state="analyzing":W.includes("incomplete")?D.state="incomplete":W.includes("out-of-date")?D.state="out-of-date":W.includes("not-analyzed")?D.state="not-analyzed":D.state="up-to-date"}),P.forEach(D=>{var W,G,Z,re,ge;for(const ve of D.entities){if(D.previewScreenshots.length+D.previewLibraryScenarios.length>=3)break;const Ee=((G=(W=ve.analyses)==null?void 0:W[0])==null?void 0:G.scenarios)||[];if(ve.entityType==="library"){const Te=Ee.find($e=>{var Ie,Oe;return((Ie=$e.metadata)==null?void 0:Ie.executionResult)||((Oe=$e.metadata)==null?void 0:Oe.error)});Te&&D.previewLibraryScenarios.push({scenario:Te,entitySha:ve.sha})}else{const Te=Ee.find($e=>{var Ie,Oe;return(Oe=(Ie=$e.metadata)==null?void 0:Ie.screenshotPaths)==null?void 0:Oe[0]});if(Te){const $e=(re=(Z=Te.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:re[0],Ie=!!((ge=Te.metadata)!=null&&ge.error);$e&&!D.previewScreenshots.includes($e)&&(D.previewScreenshots.push($e),D.previewScreenshotErrors.push(Ie))}}}});const Y=Array.from(P.values());return Y.sort((D,W)=>{if(a==="analyzed"){const re=Math.max(...D.entities.filter(ve=>{var Ne,Ee;return(Ee=(Ne=ve.analyses)==null?void 0:Ne[0])==null?void 0:Ee.createdAt}).map(ve=>new Date(ve.analyses[0].createdAt).getTime()),0),ge=Math.max(...W.entities.filter(ve=>{var Ne,Ee;return(Ee=(Ne=ve.analyses)==null?void 0:Ne[0])==null?void 0:Ee.createdAt}).map(ve=>new Date(ve.analyses[0].createdAt).getTime()),0);return j==="desc"?ge-re:re-ge}if(D.uncommittedCount>0&&W.uncommittedCount===0)return-1;if(D.uncommittedCount===0&&W.uncommittedCount>0)return 1;const G=D.lastUpdated?new Date(D.lastUpdated).getTime():0,Z=W.lastUpdated?new Date(W.lastUpdated).getTime():0;return j==="desc"?Z-G:G-Z}),Y},[I,a,j,i,d]),T=ae(()=>{let P=$;if(E!=="all"&&(P=P.filter(O=>O.state===E)),N.trim()){const O=N.toLowerCase();P=P.filter(z=>z.filePath.toLowerCase().includes(O))}return P},[$,N,E]),q=(t-1)*r,K=q+r,H=T.slice(q,K),U=Math.ceil(T.length/r),F=P=>{w(O=>{const z=new Set(O);return z.has(P)?z.delete(P):z.add(P),z})},L=()=>{R(P=>P==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:M,onChange:P=>{const O=P.target.value,z=new URLSearchParams(x);O==="all"?z.delete("entityType"):z.set("entityType",O),z.set("page","1"),v(z)},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(nt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:E,onChange:P=>k(P.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(nt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(Pn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:N,onChange:P=>C(P.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:T.length})," ",T.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:T.reduce((P,O)=>P+O.totalCount,0)})," ",T.reduce((P,O)=>P+O.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?l("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[T.filter(P=>P.uncommittedCount>0).length," ","uncommitted"," ",T.filter(P=>P.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),H.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{w(new Set(H.map(P=>P.filePath))),A(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n($o,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{w(new Set),A(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Io,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(oa,{showActions:!0,sortOrder:j,onSortChange:L}),n("div",{className:"flex flex-col gap-[3px]",children:H.map(P=>{const O=b.has(P.filePath),J=P.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(et(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||et(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||et(W,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ee=W=>{var G;return((G=s==null?void 0:s.currentEntityShas)==null?void 0:G.includes(W))||!1},Y=W=>{var G;return c!=null&&c(W)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(Z=>{var re;return(re=Z.entityShas)==null?void 0:re.includes(W.sha)}))||!1},D=W=>{h==null||h(W)};return n(ia,{filePath:P.filePath,isExpanded:O,onToggle:()=>F(P.filePath),simulationPreviews:n(la,{entities:P.entities,maxPreviews:1}),entityCount:P.totalCount,state:P.state,lastModified:P.lastUpdated,uncommittedCount:P.uncommittedCount,isUncommitted:P.uncommittedCount>0,actionButton:J?n("button",{onClick:W=>{W.stopPropagation();const G=P.entities.filter(Z=>(Z.entityType==="visual"||Z.entityType==="library")&&(et(Z,(i==null?void 0:i.jobs)||[])==="not-analyzed"||et(Z,(i==null?void 0:i.jobs)||[])==="out-of-date"||et(Z,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(G)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:P.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:P.entities.sort((W,G)=>{var Ne,Ee,Te,$e;const Z=!((Ne=W.metadata)!=null&&Ne.notExported)&&!((Ee=W.metadata)!=null&&Ee.namedExport),re=!((Te=G.metadata)!=null&&Te.notExported)&&!(($e=G.metadata)!=null&&$e.namedExport);if(Z&&!re)return-1;if(!Z&&re)return 1;const ge=W.entityType==="visual"||W.entityType==="library",ve=G.entityType==="visual"||G.entityType==="library";return ge&&!ve?-1:!ge&&ve?1:W.name.localeCompare(G.name)}).map(W=>n(ca,{entity:W,isActivelyAnalyzing:ee(W.sha),isQueued:Y(W),onGenerateSimulation:D},W.sha))},P.filePath)})}),U>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",U]}),t<U&&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 zx=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Yx({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([Vt(),on()]);return V({entities:d,currentCommit:h,page:s,filter:a,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),V({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Bx=Ue(function(){var N,C,S;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:c}=Je();lt();const[d,h]=sn(),[u,m]=_(!1);dt({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=il((C=(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun)==null?void 0:C.currentEntityShas,i),x=t||[],v=ae(()=>{const A=new Set([]);for(const E of x)A.add(E.filePath??"No File Path");return Array.from(A)},[x]),b=ae(()=>{let A=x;return u&&(A=A.filter(E=>{var k;return(k=E.metadata)==null?void 0:k.isUncommitted})),A.sort((E,k)=>{var j,R,M,I,$,T;return(j=E.metadata)!=null&&j.isUncommitted&&!((R=k.metadata)!=null&&R.isUncommitted)?-1:!((M=E.metadata)!=null&&M.isUncommitted)&&((I=k.metadata)!=null&&I.isUncommitted)?1:new Date((($=k.metadata)==null?void 0:$.editedAt)||0).getTime()-new Date(((T=E.metadata)==null?void 0:T.editedAt)||0).getTime()})},[x,u]),w=ae(()=>{var E;const A=new Set([]);for(const k of x)(E=k.metadata)!=null&&E.isUncommitted&&A.add(k.filePath??"No File Path");return Array.from(A)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Fx,{entities:b,page:s,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:w.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),Ux=Object.freeze(Object.defineProperty({__proto__:null,default:Bx,loader:Yx,meta:zx},Symbol.toStringTag,{value:"Module"})),Wx=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function Hx({request:e}){var t;try{const r=await Re();if(!r)return V({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await De(r),a=xe()||process.cwd(),o=Yi(a)||"";let i="";try{const d=await Ar();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const h=d.webapps.map(u=>u.framework).filter(Boolean);h.length>0&&(i=h.join(", "))}}catch{}const c=Hi(r);return V({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),V({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Jx({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return V({success:!1,error:"Missing feature name"},{status:400});const a=await Re();return a?(r==="clearAccess"?await nn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await nn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),V({success:!0,error:null})):V({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),V({success:!1,error:"Failed to save labs configuration"},{status:500})}}const Vx=[{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}],Ao="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",qx=[{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 Gx({onClose:e}){const t=be(null),r=be(0);return X(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let c=null,d=!1;const h=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,m=s.scrollTop>a,p=u>o;m&&p&&(s.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return s.addEventListener("scroll",h,{passive:!0}),()=>{s.removeEventListener("scroll",h),c&&clearInterval(c)}},[]),l("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"}),l("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:"×"}),l("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[l("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Ao}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Ao,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Kx({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,c;const a=(i=s.data)==null?void 0:i.error,o=(c=s.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||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"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const Qx=Ue(function(){const{labs:t,unlockCode:r,error:s}=Je(),a=Le(),o=Le(),i=Le(),[c,d]=_(""),[h,u]=_(!1),[m,p]=_(!1);dt({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:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:Vx.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[h&&n(Gx,{onClose:()=>u(!1)}),m&&n(Kx,{onClose:()=>p(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:a}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:qx.map(y=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),Zx=Object.freeze(Object.defineProperty({__proto__:null,action:Jx,default:Qx,loader:Hx,meta:Wx},Symbol.toStringTag,{value:"Module"}));function Xx(e,t,r){const[s,a]=_(()=>new Set),[o,i]=_(()=>new Set),c=be([]),d=be([]);return X(()=>{(t.length!==c.current.length||t.some((g,x)=>g!==c.current[x]))&&(c.current=t,a(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),X(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(v=>{const b=new Set(v);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function eb(e,t,r){const[s,a]=_(null),[o,i]=_(null),c=Le();X(()=>{var m,p;((m=c.data)==null?void 0:m.oldContent)!==void 0&&((p=c.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=m=>{a({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),c.submit(p,{method:"post"})},h=(m,p)=>{a({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function tb({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var h;const[o,i]=_(!1),[c,d]=_(!1);return X(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=s.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:c&&n(Lc,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,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 nb({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([w,{entities:N}])=>{const C=N.filter(S=>i(S.sha)||c(S)).map(S=>S.sha);return C.length>0?[{entityShas:C}]:[]}),v=w=>{const N=w.map(C=>et(C,x));return N.includes("analyzing")||N.includes("queued")?"analyzing":N.includes("out-of-date")?"out-of-date":N.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ae(()=>[...e].sort((w,N)=>{const C=w[1].entities.reduce((k,j)=>{var M;const R=((M=j.metadata)==null?void 0:M.editedAt)||j.updatedAt;return R?k?new Date(R)>new Date(k)?R:k:R:k},null),S=N[1].entities.reduce((k,j)=>{var M;const R=((M=j.metadata)==null?void 0:M.editedAt)||j.updatedAt;return R?k?new Date(R)>new Date(k)?R:k:R:k},null);if(!C&&!S)return 0;if(!C)return 1;if(!S)return-1;const A=new Date(C).getTime(),E=new Date(S).getTime();return d==="desc"?E-A:A-E}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(oa,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:N,entities:C,isUncommitted:S}])=>{const A=o.has(w),E=v(C),k=C.reduce((I,$)=>{var q;const T=((q=$.metadata)==null?void 0:q.editedAt)||$.updatedAt;return T?I?new Date(T)>new Date(I)?T:I:T:I},null),R=C.filter(I=>I.entityType==="visual"||I.entityType==="library").length===0;let M;return R?M=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):E==="analyzing"?M=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):E==="up-to-date"?M=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"}):E==="out-of-date"?M=n("button",{onClick:I=>{I.stopPropagation(),C.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>m($))},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"}):E==="not-analyzed"&&(M=n("button",{onClick:I=>{I.stopPropagation(),C.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>m($))},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(ia,{filePath:w,isExpanded:A,onToggle:()=>h(w),fileStatus:N,isUncommitted:S,simulationPreviews:n(la,{entities:C,maxPreviews:1}),entityCount:C.length,state:E,lastModified:k,isNotAnalyzable:R,actionButton:M,children:C.sort((I,$)=>{const T=I.entityType==="visual"||I.entityType==="library",q=$.entityType==="visual"||$.entityType==="library";return T&&!q?-1:!T&&q?1:0}).map(I=>n(ca,{entity:I,isActivelyAnalyzing:i(I.sha),isQueued:c(I),onGenerateSimulation:m},I.sha))},w)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function rb({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=ae(()=>{const w=[];return e.forEach(([N,{editedEntities:C}])=>{const S=C.filter(A=>s(A.sha)||a(A)).map(A=>A.sha);S.length>0&&w.push({entityShas:S})}),w},[e,s,a]),v=ae(()=>{const w=new Map;return e.forEach(([N,{editedEntities:C}])=>{const S=C.map(j=>et(j,x));let A;S.includes("analyzing")||S.includes("queued")?A="analyzing":S.includes("out-of-date")?A="out-of-date":S.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const E=C.reduce((j,R)=>{var I;const M=((I=R.metadata)==null?void 0:I.editedAt)||R.updatedAt;return M&&(!j||new Date(M)>new Date(j))?M:j},null),k=C.filter(j=>j.entityType==="visual"||j.entityType==="library").length;w.set(N,{state:A,lastModified:E,analyzableCount:k})}),w},[e,x]),b=ae(()=>[...e].sort((w,N)=>{const C=v.get(w[0]),S=v.get(N[0]),A=C==null?void 0:C.lastModified,E=S==null?void 0:S.lastModified;if(!A&&!E)return 0;if(!A)return 1;if(!E)return-1;const k=new Date(A).getTime(),j=new Date(E).getTime();return d==="desc"?j-k:k-j}),[e,v,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(oa,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:N,editedEntities:C}])=>{const S=r.has(w),A=v.get(w),{state:E,lastModified:k,analyzableCount:j}=A,R=j===0;let M;return R?M=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):E==="analyzing"?M=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):E==="up-to-date"?M=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"}):E==="out-of-date"?M=n("button",{onClick:I=>{I.stopPropagation(),C.filter($=>($.entityType==="visual"||$.entityType==="library")&&!s($.sha)&&!a($)).forEach($=>m($))},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"}):E==="not-analyzed"&&(M=n("button",{onClick:I=>{I.stopPropagation(),C.filter($=>($.entityType==="visual"||$.entityType==="library")&&!s($.sha)&&!a($)).forEach($=>m($))},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(ia,{filePath:w,isExpanded:S,onToggle:()=>h(w),fileStatus:N,simulationPreviews:n(la,{entities:C,maxPreviews:1}),entityCount:C.length,state:E,lastModified:k,isNotAnalyzable:R,isUncommitted:!0,actionButton:M,children:C.sort((I,$)=>{const T=I.entityType==="visual"||I.entityType==="library",q=$.entityType==="visual"||$.entityType==="library";return T&&!q?-1:!T&&q?1:0}).map(I=>n(ca,{entity:I,isActivelyAnalyzing:s(I.sha),isQueued:a(I),onGenerateSimulation:m},I.sha))},w)})})]})}function sb({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",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"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const ab=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function ob({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),c=t.get("entitySha");let d;return a==="branch"?d=Kn(s,o,i):d=rf(s),V({...d,entitySha:c})}return V({error:"Unknown action"},{status:400})}async function ib({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[c,d,h]=await Promise.all([Vt(),on(),Re()]),u=Ii(),m=Zp(),p=Xp(),f=ef(),y=a||m,g=s||p;let x=[];return y&&y!==g&&(x=Ri(g,y)),V({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),V({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 lb=Ue(function(){var ke,rt;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=Je();dt({source:"git-page"});const[p,f]=sn(),[y,g]=_(null),[x,v]=_("desc"),[b,w]=_("branch"),N=p.get("expanded")==="true",C=()=>{v(fe=>fe==="desc"?"asc":"desc")},S=Le(),A=S.data;X(()=>{s&&c&&s!==c&&S.state==="idle"&&!A&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(s)}`)},[s,c,S,A]);const E=ae(()=>{const fe=nl(r,t);return Array.from(fe.entries()).sort((ze,Be)=>ze[0].localeCompare(Be[0]))},[r,t]),k=ae(()=>{const fe=Gy(d,t,A);return Array.from(fe.entries()).sort((ze,Be)=>ze[0].localeCompare(Be[0]))},[d,t,A]),j=ae(()=>Ky(r,t),[r,t]),R=ae(()=>b==="uncommitted"?E:k,[b,E,k]),M=ae(()=>R.map(([fe])=>fe),[R]),{expandedUncommitted:I,setExpandedUncommitted:$,toggleFile:T,expandAllUncommitted:q,collapseAllUncommitted:K}=Xx(N,M,[]),{diffView:H,diffContent:U,isLoading:F,handleShowFileDiff:L,handleCloseDiff:P}=eb(c,s),O=(ke=h==null?void 0:h.metadata)==null?void 0:ke.currentRun,z=new Set((O==null?void 0:O.currentEntityShas)||[]),J=new Set(m.jobs.flatMap(fe=>fe.entityShas||[])),ee=new Set(((rt=m.currentlyExecuting)==null?void 0:rt.entityShas)||[]),{isAnalyzing:Y,handleGenerateSimulation:D,handleGenerateAllSimulations:W,isEntityBeingAnalyzed:G,isEntityPending:Z}=il(O==null?void 0:O.currentEntityShas,m),re=fe=>Z(fe)||J.has(fe.sha)||ee.has(fe.sha),ge=fe=>{fe===(a||s)?p.delete("viewBranch"):p.set("viewBranch",fe),f(p)},ve=fe=>{fe===o?p.delete("compare"):p.set("compare",fe),f(p)},Ne=()=>{const ze=R.flatMap(([Be,It])=>It.editedEntities||It.entities||[]).filter(Be=>!z.has(Be.sha)&&!J.has(Be.sha)&&!ee.has(Be.sha)&&!Z(Be));W(ze)},Ee=E.length,Te=k.length,$e=R.flatMap(([fe,ze])=>ze.editedEntities||ze.entities||[]),Ie=$e.filter(fe=>fe.entityType==="visual"||fe.entityType==="library"),Oe=Ie.length>0&&Ie.every(fe=>z.has(fe.sha)),Se=Ie.length>0&&!Oe&&Ie.every(fe=>J.has(fe.sha)||ee.has(fe.sha)),ne=Y||Oe||Se,he=Oe?"Analyzing...":Se?"Queued...":Y?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(sb,{activeTab:b,onTabChange:w,uncommittedCount:Ee,branchCount:Te})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:s,onChange:fe=>ge(fe.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(fe=>n("option",{value:fe,children:fe},fe))}),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})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:fe=>ve(fe.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(fe=>fe!==s).map(fe=>n("option",{value:fe,children:fe},fe))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:R.length})," ","modified ",R.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:$e.length})," ",$e.length===1?"entity":"entities"]})]}),R.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n($o,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:K,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(Io,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(nb,{files:k,currentBranch:s,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:I,isEntityBeingAnalyzed:G,isEntityQueued:re,sortOrder:x,onToggleFile:fe=>T(fe,I,$),onBranchChange:ve,onGenerateSimulation:D,onSortChange:C,onAnalyzeAll:Ne,analyzeAllDisabled:ne,analyzeAllText:he}),b==="uncommitted"&&n(rb,{files:E,entityImpactMap:j,expandedFiles:I,isEntityBeingAnalyzed:G,isEntityQueued:re,projectSlug:u,baseBranch:c,currentBranch:s,sortOrder:x,onToggleFile:fe=>T(fe,I,$),onShowFileDiff:L,onGenerateSimulation:D,onSortChange:C,onAnalyzeAll:Ne,analyzeAllDisabled:ne,analyzeAllText:he})]}),H&&n(tb,{diffView:H,diffContent:U,isLoading:F,entities:t,onClose:P}),y&&u&&n(At,{projectSlug:u,onClose:()=>g(null)})]})})}),cb=Object.freeze(Object.defineProperty({__proto__:null,action:ob,default:lb,loader:ib,meta:ab},Symbol.toStringTag,{value:"Module"})),av={entry:{module:"/assets/entry.client-DTvKq3TY.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-DiRdBreB.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/book-open-D_nMCFmP.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-BH2h1Ea2.js","/assets/circle-check-DyIKORY6.js","/assets/CopyButton-DmJveP3T.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.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,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-D6SEzMCu.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/Terminal-CcG8YTLx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/preload-helper-ckwbz45p.js"],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,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/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-BMvVHNXU.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.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,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/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-p9hhkjJM.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.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,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,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,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-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,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,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-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,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,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,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-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,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,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.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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,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,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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,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,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-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,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,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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,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,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-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,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,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.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-D9hemwl6.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/search-fKo7v0Zo.js","/assets/chevron-down-BH2h1Ea2.js","/assets/book-open-D_nMCFmP.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.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,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.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BpKzcsJz.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-BAXYRVEO.js","/assets/pause-DTAcYxBt.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/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,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,hasErrorBoundary:!1,module:"/assets/entity._sha._-CrjR3zZW.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/LoadingDots-BU_OAEMP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-B76aig_2.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CobE682z.js","/assets/CopyButton-DmJveP3T.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-B3aOzpCZ.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CobE682z.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-BiM6z3Do.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-B76aig_2.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/LogViewer-ceAyBX-H.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-DfuTtcJP.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-DmJveP3T.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-C96V0n15.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useToast-9FIWuYfK.js","/assets/useReportContext-O-jkvSPx.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/loader-circle-BAXYRVEO.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/editor-W_IGJ2Kd.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/Terminal-CcG8YTLx.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-FweZHj5U.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/copy-NDbZjXao.js","/assets/CopyButton-DmJveP3T.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/pause-DTAcYxBt.js","/assets/book-open-D_nMCFmP.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/files-DO4CZ16O.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-Zk7ryIM1.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/git-CFCTYk9I.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/LogViewer-ceAyBX-H.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-8daa4147.js",version:"8daa4147",sri:void 0},ov="build/client",iv="/",lv={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},cv=!0,dv=!1,uv=[],hv={mode:"lazy",manifestPath:"/__manifest"},mv="/",pv={module:Fc},fv={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:ph},"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:bh},"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:kh},"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:Ah},"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:Gh},"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:im},"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:pm},"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:gm},"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:xm},"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:vm},"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:Sm},"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:Ep},"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:Pp},"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:jp},"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:Tp},"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:Dp},"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:Op},"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:Yp},"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:Jp},"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:hf},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:pf},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:xf},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:Tf},"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:Rf},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Of},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:zf},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Uf},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Jf},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:qf},"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:Qf},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:lg},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:dg},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:yg},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:Cg},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Eg},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:jg},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Tg},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:qg},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:t0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:r0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:c0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:u0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:w0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:S0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:P0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:j0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:R0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:sy},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:iy},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:py},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:gy},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:xy},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Ty},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Ry},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Oy},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Hy},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Vy},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:nx},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:fx},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:Lx},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Ux},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Zx},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:cb}},gv=!1;export{qd as A,Hd as B,Me as C,yd as D,xd as E,Jt as F,ad as G,Uo as H,Wo as I,ld as J,Ho as K,ud as L,md as M,ov as N,iv as O,rd as P,lv as Q,cv as R,ar as S,dv as T,uv as U,hv as V,mv as W,pv as X,fv as Y,gv as Z,av as _,Zc as a,tn as b,Ut as c,xt as d,jn as e,Ys as f,Bs as g,Bo as h,Kc as i,Pd as j,_d as k,Pt as l,bt as m,qo as n,Ld as o,ir as p,ot as q,Go as r,Ko as s,Bd as t,Et as u,Qo as v,an as w,nn as x,Ya as y,Qd as z};
|