@codeyam/codeyam-cli 0.1.0-staging.a890816 → 0.1.0-staging.ad88eeb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/analyzer-template/.build-info.json +7 -7
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +9 -9
- package/analyzer-template/packages/ai/package.json +1 -1
- 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 +20 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +4 -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 +20 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.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/commands/default.js +3 -46
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/editor.js +1893 -215
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/commands/init.js +6 -1
- package/codeyam-cli/src/commands/init.js.map +1 -1
- package/codeyam-cli/src/data/techStacks.js +82 -0
- package/codeyam-cli/src/data/techStacks.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 +127 -0
- package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +635 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.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__/editorDevServer.test.js +279 -0
- package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +121 -0
- package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.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 +393 -0
- package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.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 +266 -0
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +107 -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 +221 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +213 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +1737 -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 +101 -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__/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 +246 -0
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +25 -5
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- 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/backgroundServer.js +2 -2
- 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/devServerState.js +71 -0
- package/codeyam-cli/src/utils/devServerState.js.map +1 -0
- package/codeyam-cli/src/utils/editorApi.js +73 -0
- package/codeyam-cli/src/utils/editorApi.js.map +1 -0
- package/codeyam-cli/src/utils/editorAudit.js +159 -0
- package/codeyam-cli/src/utils/editorAudit.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/editorDevServer.js +193 -0
- package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
- package/codeyam-cli/src/utils/editorEntityChangeStatus.js +44 -0
- package/codeyam-cli/src/utils/editorEntityChangeStatus.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 +81 -0
- package/codeyam-cli/src/utils/editorLoaderHelpers.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 +106 -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 +96 -0
- package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js +173 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js +347 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js +158 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
- 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 +28 -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/project.js +15 -5
- package/codeyam-cli/src/utils/project.js.map +1 -1
- 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 +112 -0
- package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +46 -16
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- 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__/editorProxy.test.js +178 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/git.js +396 -0
- package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-DmJveP3T.js → CopyButton-BPXZwM4t.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BcgbViKV.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-CQIG2qda.js} +9 -9
- package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-BzHcG7SE.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-B76aig_2.js → ScenarioViewer-0DY_NKil.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-oAf2Kqsf.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-DLxKhri3.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-BcY3q6nt.js} +6 -6
- 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-webgl-DI8QOUvO.js +58 -0
- package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-Bni3iiUj.js} +5 -5
- 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/{book-open-D_nMCFmP.js → book-open-BYOypzCa.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-C_Pmso5S.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-BVMi9VA5.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-n2FB0_Sw.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CC6AbExI.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-Csi0_PMl.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor-BuT_Huj0.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-B7ztwLut.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CrjR3zZW.js → entity._sha._-BF4oLwaE.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-D5rYBT5x.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/{files-DO4CZ16O.js → files-BZrlFE1F.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-DdZcvjGh.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-BkWJ_UNc.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-yHOVb4rc.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DaAZ_H2w.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/manifest-b0f1372e.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{memory-FweZHj5U.js → memory-Bl2rpw8u.js} +13 -10
- package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-f5-1lKBt.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{root-DiRdBreB.js → root-B_X8HS1x.js} +18 -18
- package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-Di64LWVb.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{settings-DfuTtcJP.js → settings-0OrEMU6J.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{simulations-B3aOzpCZ.js → simulations-DWT-CvLy.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-Br7MOqts.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-BLdiCuG-.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-CrAK28Bc.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
- package/codeyam-cli/src/webserver/build/server/assets/{index-BzAbACSx.js → index-CbF6h3dj.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-DRFwTJqO.js +367 -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 +383 -50
- package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
- 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 +93 -12
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +65 -112
- 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/gitignore +15 -0
- package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
- package/codeyam-cli/templates/chrome-extension-react/package.json +26 -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 +35 -0
- package/codeyam-cli/templates/editor-step-hook.py +95 -9
- package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -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 +37 -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 +112 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -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 +4 -1
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
- package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +92 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -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 +36 -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/{codeyam-dev-mode.md → skills/codeyam-dev-mode/SKILL.md} +2 -2
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +145 -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 +15 -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 +20 -0
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.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/Terminal-CcG8YTLx.js +0 -41
- 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/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/manifest-8daa4147.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-ByhSyh0W.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/xterm-DMSzMhqy.js +0 -9
- 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
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
var wc=Object.defineProperty;var da=e=>{throw TypeError(e)};var Nc=(e,t,r)=>t in e?wc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Mn=(e,t,r)=>Nc(e,typeof t!="symbol"?t+"":t,r),Cc=(e,t,r)=>t.has(e)||da("Cannot "+r);var ua=(e,t,r)=>(Cc(e,t,"read from private field"),r?r.call(e):t.get(e)),pa=(e,t,r)=>t.has(e)?da("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as d,Fragment as ue}from"react/jsx-runtime";import{PassThrough as Sc}from"node:stream";import{createReadableStreamFromReadable as kc}from"@react-router/node";import{ServerRouter as Ec,useFetcher as Oe,useLocation as Dr,useNavigate as Et,Link as de,UNSAFE_withComponentProps as We,Meta as Ac,Links as Pc,ScrollRestoration as _c,Scripts as jc,useLoaderData as Ve,useRevalidator as ht,Outlet as Mc,data as Q,useSearchParams as vn,useRouteLoaderData as Tc,useParams as ki,useActionData as $c,redirect as ma}from"react-router";import{isbot as Rc}from"isbot";import{renderToPipeableStream as Ic}from"react-dom/server";import{useState as M,useEffect as te,useCallback as ae,createContext as ro,useContext as Or,useRef as be,useMemo as ne,forwardRef as Dc,useImperativeHandle as Oc,Component as Lc}from"react";import{Settings as ha,CheckCircle2 as so,Bug as Ei,AlertTriangle as vr,Check as ft,Copy as St,Loader2 as pt,PencilRuler as Fc,HomeIcon as zc,GitCommitIcon as fa,File as Bc,RefreshCw as Yc,BookOpen as wr,FlaskConical as Uc,SettingsIcon as Wc,PanelsTopLeftIcon as Jc,ComponentIcon as Hc,FileText as ga,Code as ya,Box as Vc,List as Gc,BarChart3 as qc,Tag as Kc,Image as Un,Code2 as Ai,Activity as us,ChevronDown as lt,CircleEqual as Qc,ArrowLeft as Zc,Terminal as Nr,Search as Vn,ChevronLeft as Xc,ChevronRight as Yt,Save as ed,MessageSquare as td,Pause as Pi,ListTodo as nd,PauseCircle as rd,FileCode as Cr,GripVertical as sd,Ban as od,CheckCircle as ad,FolderOpen as id,CodeXml as ld,Zap as cd,Pencil as dd,Trash2 as ud,X as Gn,Folder as _i,Info as Is,Plus as oo,Eye as pd,FolderTree as md,ChevronsUpDown as ji,ChevronsDownUp as Mi}from"lucide-react";import"fetch-retry";import hd from"better-sqlite3";import{Pool as fd}from"pg";import*as K from"fs";import fe,{existsSync as Ot,readdirSync as gd,rmSync as ps}from"fs";import*as F from"path";import ee,{join as xa}from"path";import{OperationNodeTransformer as yd,Kysely as Ti,ParseJSONResultsPlugin as xd,SqliteDialect as bd,PostgresDialect as vd,sql as at}from"kysely";import*as wd from"kysely/helpers/sqlite";import*as Nd from"kysely/helpers/postgres";import Ye from"typescript";import*as ve from"fs/promises";import we,{writeFile as On,readFile as Ds,mkdir as Cd}from"fs/promises";import*as ao from"os";import Os from"os";import Sd from"prompts";import Sr from"chalk";import*as kd from"crypto";import qn,{randomUUID as io,createHmac as Ed}from"crypto";import{execSync as Ae,spawn as At,exec as lo}from"child_process";import{fileURLToPath as Lr}from"url";import{promisify as co}from"util";import Ad from"dotenv";import Pd,{EventEmitter as Fr}from"events";import{v4 as _d}from"uuid";import uo from"http";import $i from"net";import{WebSocket as Ri}from"ws";import"node-pty";import jd from"openai";import Md from"p-queue";import ba from"p-retry";import{DynamoDBClient as zr,PutItemCommand as Td}from"@aws-sdk/client-dynamodb";import{LRUCache as po}from"lru-cache";import"pluralize";import"piscina";import $d from"json5";import{marshall as Rd}from"@aws-sdk/util-dynamodb";import Id from"v8";import{Prism as Dd}from"react-syntax-highlighter";import{vscDarkPlus as Od}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ld}from"node:crypto";import{minimatch as Ls}from"minimatch";import Fd from"react-markdown";import zd from"remark-gfm";import Bd from"react-diff-viewer-continued";const Ii=5e3;function Yd(e,t,r,s,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((a,i)=>{let l=!1,c=e.headers.get("user-agent"),p=c&&Rc(c)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>h(),Ii+1e3);const{pipe:m,abort:h}=Ic(n(Ec,{context:s,url:e.url}),{[p](){l=!0;const f=new Sc({final(g){clearTimeout(u),u=void 0,g()}}),y=kc(f);r.set("Content-Type","text/html"),m(f),a(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const Ud=Object.freeze(Object.defineProperty({__proto__:null,default:Yd,streamTimeout:Ii},Symbol.toStringTag,{value:"Module"}));function Wd({id:e,selected:t,onClick:r,icon:s,name:o}){const[a,i]=M(!1);te(()=>{i(!0)},[]);const l=ae(()=>{r==null||r(e)},[r,e]);return d("button",{className:`
|
|
2
|
+
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
+
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
+
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
+
`,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:a&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:o})]})}const Br="/assets/cy-logo-cli-CCKUIm0S.svg";function Jd(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 Hd({content:e,className:t=""}){const[r,s]=M(!1),o=ae(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(a=>{console.error("Failed to copy:",a)})},[e]);return n("button",{onClick:o,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?d(ue,{children:[n(ft,{size:14}),"Copied"]}):d(ue,{children:[n(St,{size:14}),"Copy"]})})}function Di({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:o}){const[a,i]=M(""),[l,c]=M(s),[p,u]=M(!1),[m,h]=M(!1),[f,y]=M(null),[g,x]=M(null),v=Oe(),b=v.state!=="idle",w=!!(r.scenarioId||r.analysisId),S=r.analysisId||r.scenarioId||"",E=()=>{const A=`/codeyam-diagnose ${S}`;return a.trim()?`${A} ${a.trim()}`:A};if(v.data&&!m&&!g){const A=v.data;A.success&&A.reportId?(h(!0),y(A.reportId)):A.error&&x(A.error)}const k=async()=>{x(null);const A=new FormData;if(A.append("issueType","other"),A.append("description",a),A.append("email",l),A.append("source",r.source),A.append("entitySha",r.entitySha||""),A.append("scenarioId",r.scenarioId||""),A.append("analysisId",r.analysisId||""),A.append("currentUrl",r.currentUrl),A.append("entityName",r.entityName||""),A.append("entityType",r.entityType||""),A.append("scenarioName",r.scenarioName||""),A.append("errorMessage",r.errorMessage||""),o)try{const P=await(await fetch(o)).blob();A.append("screenshot",P,"screenshot.jpg")}catch(T){console.error("Failed to convert screenshot:",T)}v.submit(A,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},N=()=>{i(""),u(!1),h(!1),y(null),x(null),t()},C=A=>{A.key==="Escape"&&N()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:C,children:d("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[d("div",{className:"flex items-center justify-between mb-6",children:[d("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(ha,{size:24,style:{strokeWidth:1.5}})}):m?n(so,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Ei,{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:N,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?d("div",{children:[d("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),d("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:N,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):d("div",{children:[d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[d("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:Jd(r)}),n("button",{type:"button",onClick:()=>u(!p),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:p?"Hide":"Details"})]}),p&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),o&&d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:a,onChange:A=>i(A.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&&d(ue,{children:[d("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),d("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:E()}),n(Hd,{content:E(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),d("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),d("div",{className:w?"opacity-75":"",children:[w&&d("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:A=>c(A.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),d("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(vr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),d("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),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&&d("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(vr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),d("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:N,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 k(),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?d(ue,{children:[n("div",{className:"animate-spin",children:n(ha,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const va={source:"navbar"},mo=ro(void 0);function Vd({children:e}){const[t,r]=M(va),s=ae(a=>{r(a)},[]),o=ae(()=>{r(va)},[]);return n(mo.Provider,{value:{contextData:t,setContextData:s,resetContextData:o},children:e})}function gt(e){const t=Or(mo),r=be(t);te(()=>{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 Gd(){const e=Or(mo),t=Dr();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 qd({labs:e,isAdmin:t,editorMode:r}){var k;const s=Dr(),o=Et(),[a,i]=M(),[l,c]=M(!1),[p,u]=M(!1),[m,h]=M(null),f=Oe();te(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((k=f.data)==null?void 0:k.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,v=[{id:"editor",icon:n(Fc,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(zc,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:d("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x},{id:"git",icon:n(fa,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(Bc,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(Yc,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(wr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Uc,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Wc,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(fa,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Jc,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Hc,{style:g}),link:"/components",name:"Components",hidden:!0}],b=ae(N=>{const C=v.find(A=>A.id===N);C!=null&&C.link&&o(C.link),i(A=>A===N?void 0:N)},[v,o]);te(()=>{const N={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[C,A]of Object.entries(N))if(A.some(T=>T==="/"?s.pathname==="/":s.pathname.includes(T))){i(C);return}i(void 0)},[s]);const w=async()=>{u(!0);try{const{default:N}=await import("html2canvas-pro"),A=(await N(document.body)).toDataURL("image/jpeg",.8);h(A),c(!0)}catch(N){console.error("Screenshot capture failed:",N),c(!0)}finally{u(!1)}},S=()=>{c(!1),h(null)},E=Gd();return d(ue,{children:[d("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[d("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(de,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Br,alt:"CodeYam",className:"h-6"})})}),v.filter(N=>!N.hidden).map(N=>n(Wd,{id:N.id,selected:N.id===a,onClick:b,icon:N.icon,name:N.name},`sidebar-button-${N.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void w(),disabled:p,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:p?n(pt,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Ei,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:p?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),l&&n(Di,{isOpen:!0,onClose:S,context:E,defaultEmail:y,screenshotDataUrl:m??void 0})]})}const Oi=ro(void 0);function Kd({children:e}){const[t,r]=M([]),s=ae((a,i="info",l=5e3)=>{const p={id:`toast-${Date.now()}-${Math.random()}`,message:a,type:i,duration:l};r(u=>[...u,p])},[]),o=ae(a=>{r(i=>i.filter(l=>l.id!==a))},[]);return n(Oi.Provider,{value:{toasts:t,showToast:s,closeToast:o},children:e})}function ho(){const e=Or(Oi);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Qd({toast:e,onClose:t}){te(()=>{const o=e.duration||5e3;if(o>0){const a=setTimeout(()=>{t(e.id)},o);return()=>clearTimeout(a)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return d("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Zd({toasts:e,onClose:t}){return e.length===0?null:d("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
+
@keyframes slideIn {
|
|
8
|
+
from {
|
|
9
|
+
transform: translateX(400px);
|
|
10
|
+
opacity: 0;
|
|
11
|
+
}
|
|
12
|
+
to {
|
|
13
|
+
transform: translateX(0);
|
|
14
|
+
opacity: 1;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
`}),e.map(r=>n(Qd,{toast:r,onClose:t},r.id))]})}function Pt(e,t){const[r,s]=M(""),[o,a]=M(!1),[i,l]=M(null),[c,p]=M(!1);te(()=>{t&&(p(!1),a(!1),l(null))},[t]),te(()=>{if(!e||!t){t||s("");return}const m=async()=>{if(!c)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){a(!1),p(!1),l(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();l(b),p(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&a(!0)}}catch{}};m().catch(()=>{});const h=setInterval(()=>{m().catch(()=>{})},500);return()=>clearInterval(h)},[e,t,c]);const u=ae(()=>{s(""),a(!1),l(null),p(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:o,resetLogs:u}}function Ft({projectSlug:e,onClose:t}){const[r,s]=M("Loading logs..."),[o,a]=M(!0),[i,l]=M(!0),[c,p]=M("all"),u=be(null);return te(()=>{const m=async()=>{try{const h=await fetch(`/api/logs/${e}`);if(h.ok){const f=await h.text();if(c==="all")s(f);else{const y=f.trim().split(`
|
|
19
|
+
`).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=c});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
+
`))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${h.status} - ${await h.text()}`)}catch(h){s(`Error fetching logs: ${h.message}`)}};if(m().catch(()=>{}),o){const h=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(h)}},[e,o,i,c]),te(()=>{const m=h=>{h.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:d("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:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:m=>p(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"})]})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:o,onChange:m=>a(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>l(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function tt({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,o=t==="large"?18:14,a=t==="large"?32:18,i=()=>{switch(e){case"library":return n(Ai,{size:o,color:s.iconColor});case"visual":return n(Un,{size:o,color:s.iconColor});case"type":return n(Kc,{size:o,color:s.iconColor});case"data":return n(qc,{size:o,color:s.iconColor});case"index":return n(Gc,{size:o,color:s.iconColor});case"functionCall":return n(ya,{size:o,color:s.iconColor});case"class":return n(Vc,{size:o,color:s.iconColor});case"method":return n(ya,{size:o,color:s.iconColor});case"other":return n(ga,{size:o,color:s.iconColor});default:return n(ga,{size:o,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${a}px`,height:`${a}px`},children:i()})}function Li({filePath:e,maxLength:t=60,className:r,style:s}){const a=((l,c)=>{if(l.length<=c)return l;const p="...",u=c-p.length,m=Math.ceil(u*.4),h=Math.floor(u*.6),f=l.slice(0,m),y=l.slice(-h),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>m*.5?f.slice(0,g+1):f,b=x!==-1&&x<h*.5?y.slice(x):y;return`${v}${p}${b}`})(e,t),i=a!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:a})}function ms({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:o=!1,scenarioCount:a=0,additionalContent:i}){return d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"flex items-center gap-1",children:[n(tt,{type:e.entityType||"other"}),d(de,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&a>0&&` (${a})`]}),n(Li,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const hs={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Xd({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:o=0,queueJobs:a=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var H,W,B;const[c,p]=M(!1),[u,m]=M(!1),[h,f]=M(null),[y,g]=M(new Set),[x,v]=M(new Set),[b,w]=M(!1),S=!!i||a.length>0,E=!!i,k=(i==null?void 0:i.entities)||r,N=!!(e!=null&&e.analysisCompletedAt),C=(e==null?void 0:e.readyToBeCaptured)??0,A=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||N&&(C===0||A>=C);const T=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,P=S,{lastLine:_}=Pt(t,P),$=E||a.length>0,I=new Set(((H=i==null?void 0:i.entities)==null?void 0:H.map(D=>D.sha))||[]),R=l.filter(D=>!(D.currentEntityShas||[]).some(j=>I.has(j))),Y=(()=>{const O=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&T){const j=e.analysisCompletedAt||e.createdAt;if(new Date(j).getTime()>O)return!0}if(R.length>0){const j=R[0],q=j.analysisCompletedAt||j.archivedAt||j.createdAt;if(q&&new Date(q).getTime()>O)return!0}return!1})();return te(()=>{const D=(i==null?void 0:i.id)||null;S&&!u&&D!==h&&m(!0),!S&&h!==null&&f(null)},[S,i==null?void 0:i.id,u,h]),d(ue,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&d("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:[$?n(pt,{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(us,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity: No Activity Yet"}),$&&n("button",{onClick:D=>{D.stopPropagation(),p(!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&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[$?n(pt,{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(us,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>p(!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(lt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),d("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[$&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(us,{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:k.length>0?d("div",{className:"space-y-1.5",children:[(b?k:k.slice(0,3)).map(D=>n(ms,{entity:D,nameSize:"11px",pathSize:"10px",pathMaxLength:150},D.sha)),k.length>3&&n("button",{onClick:()=>w(D=>!D),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:hs,"aria-label":b?"Show fewer entities":`Show ${k.length-3} more entities`,children:b?"Show less":`+${k.length-3} more`}),_&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:_})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((D,O)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:D},O)),i.entityNames.length>5&&d("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):d("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((W=i.entityShas)==null?void 0:W.length)||0," ",((B=i.entityShas)==null?void 0:B.length)===1?"entity":"entities","..."]}),_&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:_})]})})]}),a.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Qc,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:a.map(D=>{var q,V;const O=y.has(D.id),j=O?D.entities:D.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:D.entities.length>0?d("div",{className:"space-y-1.5",children:[j.map(U=>n(ms,{entity:U,nameSize:"10px",pathSize:"9px",pathMaxLength:120},U.sha)),D.entities.length>3&&n("button",{onClick:()=>{g(U=>{const Z=new Set(U);return Z.has(D.id)?Z.delete(D.id):Z.add(D.id),Z})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:hs,"aria-label":O?"Show fewer entities":`Show ${D.entities.length-3} more entities`,children:O?"Show less":`+${D.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[D.type==="analysis"&&n(ue,{children:D.entityNames&&D.entityNames.length>0?d("div",{className:"space-y-0.5",children:[D.entityNames.slice(0,5).map((U,Z)=>n("div",{children:U},Z)),D.entityNames.length>5&&d("div",{className:"italic",children:["+",D.entityNames.length-5," more"]})]}):`Analyzing ${((q=D.entityShas)==null?void 0:q.length)||0} ${((V=D.entityShas)==null?void 0:V.length)===1?"entity":"entities"}`}),D.type==="recapture"&&"Recapturing scenario",D.type==="debug-setup"&&"Setting up debug environment"]})},D.id)})})]}),Y&&R.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(so,{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:R.slice(0,3).map((D,O)=>{const j=D.entities||[],q=D.analysisCompletedAt||D.archivedAt||D.createdAt||"",V=(()=>{if(!q)return"";const L=Date.now()-new Date(q).getTime(),J=Math.floor(L/6e4),G=Math.floor(L/36e5);return G>0?`${G}h ago`:J>0?`${J}m ago`:"just now"})(),U=x.has(O),z=(U?j:j.slice(0,3)).map(L=>{var J,G,X;return{...L,scenarioCount:((X=(G=(J=L.analyses)==null?void 0:J[0])==null?void 0:G.scenarios)==null?void 0:X.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:j.length>0&&d("div",{className:"space-y-1.5",children:[z.map((L,J)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ms,{entity:L,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:L.scenarioCount})}),J===0&&V&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:V})]},L.sha)),j.length>3&&n("button",{onClick:()=>{v(L=>{const J=new Set(L);return J.has(O)?J.delete(O):J.add(O),J})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:hs,"aria-label":U?"Show fewer entities":`Show ${j.length-3} more entities`,children:U?"Show less":`+${j.length-3} more`})]})},O)})})]})]}),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 →"})})]})]}),c&&t&&n(Ft,{projectSlug:t,onClose:()=>p(!1)})]})}function rt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Kn(e){const{file_id:t,project_id:r,commit_id:s,file_path:o,entity_type:a,entity_branches:i,analyses:l,commit:c,created_at:p,updated_at:u,...m}=e,h=(i??[]).map(g=>g.branch_id),f=l?l.map(_t):void 0,y=c?sn(c):void 0;return rt({...m,fileId:t,projectId:r,commitId:s,filePath:o,entityType:a,commit:y,analyses:f,branchIds:h,createdAt:p,updatedAt:u})}function fo(e){return rt({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 go(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:o,created_at:a,updated_at:i,github_token:l,configuration:c,team_id:p,...u}=e;return rt({...u,branches:t?t.map(yn):void 0,files:r?r.map(fo):void 0,analyzedAt:s,contentChangedAt:o,createdAt:a,updatedAt:i})}function eu(e){const{id:t,project_id:r,user_id:s,scenario_id:o,thumbs_up:a,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return rt({id:t,projectId:r,userId:s,scenarioId:o,thumbsUp:!!a,user:l})}function tu(e){const{id:t,project_id:r,user_id:s,scenario_id:o,text:a,created_at:i,updated_at:l,user:c}=e,p=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return rt({id:t,projectId:r,userId:s,scenarioId:o,text:a,createdAt:i,updatedAt:l,user:p})}function Fi(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:o,user_scenarios:a,scenario_comments:i,approved:l,...c}=e,p=o?_t(o):void 0,u=a?a.map(eu):void 0,m=i?i.map(tu):void 0;return rt({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:p,userScenarios:u,comments:m})}function nu(e){return rt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?_t(e.analysis):void 0,entity:e.entity?Kn(e.entity):void 0,branch:e.branch?yn(e.branch):void 0,createdAt:e.created_at})}function _t(e){const{project_id:t,commit_id:r,file_id:s,file_path:o,entity_sha:a,entity_type:i,entity_name:l,previous_analysis_id:c,file:p,entity:u,commit:m,project:h,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:S,updated_at:E,indirect:k,...N}=e,C=u?Kn(u):void 0,A=p?fo(p):void 0,T=h?go(h):void 0,P=m?sn(m):void 0,_=f?f.map(Fi):void 0,$=y?y.map(nu):void 0,I=$?$.map(R=>R.branch):void 0;return rt({...N,projectId:t,commitId:r,fileId:s,filePath:o,entitySha:a,entityType:i,entityName:l,previousAnalysisId:c,entity:C,file:A,commit:P,project:T,scenarios:_,analysisBranches:$,branches:I,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:w,createdAt:S,updatedAt:E,indirect:!!k})}function yo(e){return rt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?sn(e.commit):void 0,branch:e.branch?yn(e.branch):void 0})}function ru(e){const{project_id:t,commit_id:r,created_at:s,updated_at:o,success:a,...i}=e;return rt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:o,success:!!a})}function sn(e){const{project_id:t,branch_id:r,branch:s,background_jobs:o,merged_branch_id:a,mergedBranch:i,ai_message:l,html_url:c,author:p,analyses:u,entities:m,commit_branches:h,committed_at:f,analyzed_at:y,...g}=e,x=s?yn(s):void 0,v=i?yn(i):void 0,b=(o==null?void 0:o.length)>0?ru(o[o.length-1]):void 0,w=(u??[]).map(_t),S=(m??[]).map(Kn),E=(h==null?void 0:h.length)>0?h.map(yo):void 0;return p&&(p.username=p.preferredUsername??p.username),rt({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:a,mergedBranch:v,aiMessage:l,htmlUrl:c,author:p,analyses:w,entities:S,commitBranches:E,committedAt:f,analyzedAt:y})}function yn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:o,active_at:a,created_at:i,updated_at:l,primary:c,...p}=e,u=s?s.map(sn):void 0,m=o?o.flatMap(h=>_t(h.analysis)):void 0;return rt({...p,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:a,createdAt:i,updatedAt:l,primary:!!c})}var Rr;class su{constructor(){pa(this,Rr,new ou)}transformQuery(t){return ua(this,Rr).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Rr=new WeakMap;class ou extends yd{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 ie=()=>null,au={analyzed_at:ie(),configuration:ie(),content_changed_at:ie(),created_at:ie(),description:ie(),github_token:ie(),id:ie(),metadata:ie(),name:ie(),path:ie(),slug:ie(),team_id:ie(),updated_at:ie()},iu=Object.keys(au),lu={active:ie(),analysis_id:ie(),branch_id:ie(),created_at:ie(),entity_sha:ie(),id:ie()},cu=Object.keys(lu),du={active_at:ie(),content_changed_at:ie(),created_at:ie(),id:ie(),metadata:ie(),name:ie(),primary:ie(),project_id:ie(),ref:ie(),sha:ie(),updated_at:ie()},zi=Object.keys(du),uu={ai_message:ie(),analyzed_at:ie(),author_github_username:ie(),branch_id:ie(),committed_at:ie(),created_at:ie(),files:ie(),html_url:ie(),id:ie(),merged_branch_id:ie(),message:ie(),metadata:ie(),project_id:ie(),sha:ie(),title:ie(),url:ie()},Bi=Object.keys(uu),pu=Bi.filter(e=>e!=="files"),mu={commit_id:ie(),created_at:ie(),description:ie(),documentation:ie(),entity_type:ie(),file_id:ie(),file_path:ie(),metadata:ie(),name:ie(),project_id:ie(),quality:ie(),sha:ie(),updated_at:ie()},Yi=Object.keys(mu),hu={active:ie(),branch_id:ie(),entity_sha:ie()},fu=Object.keys(hu),gu={created_at:ie(),deleted:ie(),id:ie(),metadata:ie(),name:ie(),path:ie(),project_id:ie(),updated_at:ie()},yu=Object.keys(gu),xu={analysis_id:ie(),approved:ie(),created_at:ie(),description:ie(),id:ie(),metadata:ie(),name:ie(),previous_version_id:ie(),project_id:ie()},kr=Object.keys(xu),bu=!!on("ENABLE_QUERY_LOGGING"),vu=!!on("ENABLE_QUERY_ERROR_LOGGING");on("USE_LOCAL_POSTGRESQL_FOR_TESTING");let rr;function Me(){if(!rr){const e=Wi();if(e==="sqlite")rr=wu();else if(e==="postgresql")rr=Nu();else throw new Error(`Unknown database type: ${e}`)}return rr}function wu(e){if(e||(e=on("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=F.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const s=new hd(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const o=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&o.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(o){console.error("CodeYam DB ERROR: Failed to verify database schema:",o)}return new Ti({dialect:new bd({database:s}),plugins:[new xd,new su],log:Ui})}function Nu(){const e=Su();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new fd({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Ti({dialect:new vd({pool:t}),log:Ui})}let fs=null;function ln(){return fs||(fs=Cu(Wi())),fs}function Ui(e){e.level==="error"?vu&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):bu&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Cu(e){if(e==="sqlite")return wd;if(e==="postgresql")return Nd;throw new Error(`Unknown database type: ${e}`)}function Wi(){if(on("SQLITE_PATH"))return"sqlite";if(on("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Su(){const e=on("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function on(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var He=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(He||{});const Yr="Default Scenario";let ku="<main>";function Eu(){return ku}function wa(e,...t){_e(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function _e(...e){const t=Eu(),r=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
21
|
+
${o.stack}`:typeof o=="object"?Au(o):String(o)}).filter(Boolean).join(`
|
|
22
|
+
`),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
|
|
23
|
+
`);return}console.log(s.replace(/\n/g,"\r"))}function Au(e,t=2){function r(s,o=new WeakMap){return s===null||typeof s!="object"?s:o.has(s)?`"[Circular: ${s.constructor.name}]"`:(o.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const c=r(l,o);return typeof l=="string"?`"${c}"`:c}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let c;return typeof l>"u"?null:(typeof l=="function"?c=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?c=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?c=r(l,o):typeof l=="string"?c=`"${l.replace(/"/g,'\\"')}"`:c=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${c}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const o=r(e);if(!t)return o;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(a){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:a,pureStringifyError:s,serialized:o}),o}}}function Er(e,t){try{let r=function(a){var i,l;if(Ye.isFunctionDeclaration(a)&&Tn(a)){const c=((i=a.name)==null?void 0:i.text)||"default",p=a.getText(s),u=gs(a);o.push({name:c,code:p,sha:Gt(t,c,p),entityType:"function",isDefault:u})}else if(Ye.isClassDeclaration(a)&&Tn(a)){const c=((l=a.name)==null?void 0:l.text)||"default",p=a.getText(s),u=gs(a),m=p.includes("React.")||p.includes("jsx")||p.includes("tsx");o.push({name:c,code:p,sha:Gt(t,c,p),entityType:m?"component":"class",isDefault:u})}else if(Ye.isInterfaceDeclaration(a)&&Tn(a)){const c=a.name.text,p=a.getText(s);o.push({name:c,code:p,sha:Gt(t,c,p),entityType:"interface",isDefault:!1})}else if(Ye.isTypeAliasDeclaration(a)&&Tn(a)){const c=a.name.text,p=a.getText(s);o.push({name:c,code:p,sha:Gt(t,c,p),entityType:"type",isDefault:!1})}else if(Ye.isVariableStatement(a)&&Tn(a)){const c=gs(a);a.declarationList.declarations.forEach(p=>{var u;if(Ye.isIdentifier(p.name)){const m=p.name.text,h=a.getText(s),f=((u=p.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));o.push({name:m,code:h,sha:Gt(t,m,h),entityType:y?"component":"variable",isDefault:c})}})}else if(Ye.isExportAssignment(a)){const c=a.getText(s);o.push({name:"default",code:c,sha:Gt(t,"default",c),entityType:"unknown",isDefault:!0})}else if(Ye.isExportDeclaration(a)&&a.exportClause&&Ye.isNamedExports(a.exportClause)){const c=a.getText(s);for(const p of a.exportClause.elements){const u=p.name.text;o.push({name:u,code:c,sha:Gt(t,u,c),entityType:"unknown",isDefault:!1})}}Ye.forEachChild(a,r)};const s=Ye.createSourceFile(t,e,Ye.ScriptTarget.Latest,!0),o=[];return r(s),o}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Tn(e){if(!Ye.canHaveModifiers(e))return!1;const t=Ye.getModifiers(e);return t?t.some(r=>r.kind===Ye.SyntaxKind.ExportKeyword):!1}function gs(e){if(!Ye.canHaveModifiers(e))return!1;const t=Ye.getModifiers(e);return t?t.some(r=>r.kind===Ye.SyntaxKind.DefaultKeyword):!1}function Gt(e,t,r){const s=qn.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Pu(e){var p;const{webapp:t,port:r,environmentVariables:s,packageManager:o}=e,a=t==null?void 0:t.startCommand;if(!a)return`${o} ${o==="npm"?"run ":""}dev`;const i=((p=a.args)==null?void 0:p.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${m}'`)}if(a.env)for(const[u,m]of Object.entries(a.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return a.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${a.command} ${i.join(" ")}`}function _u(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=F.normalize(e),s=[...t].sort((o,a)=>{var i,l;return(((i=a.path)==null?void 0:i.length)??0)-(((l=o.path)==null?void 0:l.length)??0)});for(const o of s){const a=F.normalize(o.path??".");if(a==="."||r.startsWith(a+F.sep)||r===a)return o}return t[0]}function ju(e){const{filePath:t,webapps:r,environmentVariables:s,port:o,packageManager:a}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=_u(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Pu({webapp:i,port:o,environmentVariables:s,packageManager:a});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??a,startCommand:l,url:`http://localhost:${o}/static/codeyam-sample`}}function Ur(e,t,r=[]){const s=Array.isArray(t)?t:[t];return o=>o.columns(s).doUpdateSet(a=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,a.ref(`excluded.${l}`)]))})}function Mu(e){const{jsonObjectFrom:t}=ln();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function Tu({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 $u(...e){try{const t=qn.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 ys(e,t){return t.map(r=>Ru(e,r))}function Ru(e,t){return at` ${at.ref(e)}.${at.ref(t)}`.as(t)}function Iu(e,t,r){return t.map(s=>Du(e,s,r))}function Du(e,t,r){return at` ${at.ref(e)}.${at.ref(t)}`.as(`_cy_${r}:${t}`)}function Ou(e,...t){const r={};for(const[s,o]of Object.entries(e)){const a=s.match(/^_cy_(.+?):(.+)$/);if(a){const[,i,l]=a;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=o}return r}const Lu=50;function Fu(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 Na({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:o,commitIds:a,branchCommitSha:i,limit:l,excludeMetadata:c}){const p=Me(),{jsonObjectFrom:u,jsonArrayFrom:m}=ln();let h=c?p.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"]):p.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(a){if(a.length===0)return null;h=h.where("commit_id","in",a)}return s&&(h=h.where("entity_name","=",s)),o&&(h=h.where("entity_sha","in",o)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),c?p.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(ys("scenarios",kr)).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")]):p.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(ys("entities",Yi)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(ys("scenarios",kr)).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 zt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:o}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:o,key:"commitIds"}}).find(([c,{arr:p}])=>(p==null?void 0:p.length)>0);let l=[];if(i){const[c,{arr:p,key:u}]=i,m=Fu(p,Lu),h=[];for(let f=0;f<m.length;f++){const y=m[f],x=await Na({...e,[u]:y}).execute();x&&h.push(...x)}l=h}else{const p=await Na(e).execute();if(!p||p.length===0)return _e("CodeYam: No analyses found",null,e),null;l=p}return l.length===0?null:l.map(_t)}catch(a){return _e("CodeYam Error: Database error in loadAnalyses",a,e),null}}function zu(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=ln();let o=e.selectFrom("analysis_branches").select(cu).select(a=>s(a.selectFrom("branches").select(zi).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(o=t(o)),r(o)}async function jt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}){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):l?g=g.where("analyzed_tree_sha","=",l):s&&(g=g.where("file_id","=",s)),a&&(g=g.where("entity_name","=",a)),o?g=g.where("commit_id","=",o):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=ln();g=g.select(S=>{const E=[];return E.push(x(S.selectFrom("entities").select(Yi).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&E.push(x(S.selectFrom("files").select(yu).whereRef("files.id","=","analyses.file_id")).as("file")),p&&E.push(x(S.selectFrom("projects").select(iu).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&E.push(v(S.selectFrom("scenarios").select(kr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),h&&E.push(zu(S,k=>k.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&E.push(x(S.selectFrom("commits").select(Bi).select(k=>Mu(k).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),E});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:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}),null;if(w>100&&u){const S=b.commit,E=S!=null&&S.files?JSON.stringify(S.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${w}ms (files: ${Math.round(E/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return _t(b)}catch(g){return _e("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:o,entityName:a,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}),null}}async function Ji({projectId:e,ids:t,names:r,includeInactive:s}){const o=Me();try{let a=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];a=a.where("id","in",t)}if(r){if(r.length===0)return[];a=a.where("name","in",r)}return s||(a=a.where("active_at","is not",null)),(await a.execute()).map(yn)}catch(a){return _e("CodeYam Error: Database error loading branches",a,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Bu({projectId:e,commitId:t,branchId:r,active:s,includeBranches:o}){const a=Me();try{let i=a.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,p=>p.select(Iu("branches",zi,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(p=>Ou(p,"branch")).map(yo)}catch(i){return _e("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:o}),null}}async function Yu(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(a=>{a.branch_id&&s.add(a.branch_id),a.merged_branch_id&&s.add(a.merged_branch_id)}),s.size===0)return new Map;const o=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(o.map(a=>[a.id,a]))}catch(r){return _e("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Uu(e){if(e.length===0)return new Map;const t=Me(),{jsonObjectFrom:r,jsonArrayFrom:s}=ln();try{const o=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(kr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),a=new Map;return o.forEach(i=>{const l=a.get(i.commit_id)||[];l.push(i),a.set(i.commit_id,l)}),a}catch(o){return _e("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function Wu(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(o=>{const a=s.get(o.commit_id)||[];a.push(o),s.set(o.commit_id,a)}),s}catch(r){return _e("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Ar({projectId:e,branchId:t,ids:r,shas:s,fileNames:o,limit:a=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=Me(),{jsonObjectFrom:c}=ln(),p=Date.now();try{let u;if(i){const b=pu.map(w=>`commits.${w}`);u=l.selectFrom("commits").select(b)}else u=l.selectFrom("commits").selectAll("commits").select(b=>[c(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(o&&o.length>0){const b=at.join(o.map(w=>at`${w}`),at`, `);u=u.where(at`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${at.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(a).execute(),h=Date.now()-p;if(!m||m.length===0)return[];if(h>100){const b=m.reduce((w,S)=>w+(S.files?JSON.stringify(S.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${h}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(sn);const f=m.map(b=>b.id),[y,g,x]=await Promise.all([Yu(f),Uu(f),Wu(f)]);return m.map(b=>{const w=b.branch_id?y.get(b.branch_id):void 0,S=b.merged_branch_id?y.get(b.merged_branch_id):void 0,E=g.get(b.id)||[],k=x.get(b.id)||[];return{...b,branch:w,mergedBranch:S,analyses:E,entities:k}}).map(sn)}catch(u){return _e("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:a}),[]}}async function et({projectId:e,branchId:t,fileIds:r,filePaths:s,names:o,shas:a,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||o&&o.length==0||a&&a.length==0)return[];if(a&&a.length>50){const c=[];for(let p=0;p<a.length;p+=50){const u=a.slice(p,p+50),m=await et({projectId:e,branchId:t,fileIds:r,filePaths:s,names:o,shas:u,excludeMetadata:i});m&&c.push(...m)}return c}const l=Me();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!a,m=>m.where("entities.sha","in",a)).$if(!!s,m=>m.where("entities.file_path","in",s)).$if(!!o,m=>m.where("entities.name","in",o)).$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:a}),null):u.map(Kn)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:a}),null}}function Ju(e,t){const{jsonArrayFrom:r}=ln();let s=e.selectFrom("entity_branches").select(fu);return t&&(s=t(s)),r(s)}async function Hi({projectId:e,sha:t}){const r=Me();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>Ju(o,a=>a.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?Kn(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 xs=1e3;async function Vi({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const p=t.slice(c,c+50),u=await Vi({projectId:e,filePaths:p,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const o=Me(),a=[];let i=0;try{for(;;){let l=o.selectFrom("files").selectAll().where("project_id","=",e).limit(xs).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(s){if(s.length===0)return[];l=l.where("name","in",s)}const c=await l.execute();if(!c||c.length===0||(a.push(...c),c.length<xs))break;i+=xs}return a==null?void 0:a.map(fo)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Hu({id:e,slug:t,withBranches:r,withFiles:s,silent:o}){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 l=await i.executeTakeFirst();if(!l)return o||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:s}),null;const c=go(l);return s&&(c.files=await Vi({projectId:c.id})),r&&(c.branches=await Ji({projectId:c.id,includeInactive:!1})),c}catch(a){return o||console.log("CodeYam Error: Error loading project",a),null}}function Pr(e,t){const r={...e};for(const s in t){const o=t[s],a=e[s];o!=null&&typeof o=="object"&&!Array.isArray(o)&&a!==void 0&&a!==null&&typeof a=="object"&&!Array.isArray(a)?r[s]=Pr(a,o):o!==void 0&&(r[s]=o)}return r}async function Lt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:o,updateCallback:a}){for(let c=0;c<=4;c++)try{return await Me().transaction().execute(async p=>{var f,y;const u=await p.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:",o)),r=Pr(r??{},{currentRun:s});else if(!r&&!a)return m;const h=r?Pr(m,r):m;if(o&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((y=h.historicalRuns)==null?void 0:y.length)||0}`);const g={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(g,null,2)),h.historicalRuns=[...h.historicalRuns||[],g],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(x=>({entityShas:x.currentEntityShas,archivedAt:x.archivedAt,completed:{analyses:x.analysesCompleted,captures:x.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}a&&await a(h);try{return await p.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?h:(_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(p){const u=p instanceof Error&&p.message.includes("database is locked");if(u&&c<4){const m=250*Math.pow(2,c);await new Promise(h=>setTimeout(h,m));continue}return _e(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${c+1} attempts`:""}`,p),null}return null}async function Gi(e,t,r="analysis"){try{return await Me().transaction().execute(async s=>{const o=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return _e(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const a=_t(o);return t(a.metadata,a),await s.updateTable("analyses").set({metadata:JSON.stringify(a.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?a.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 wn(e,t,r="capture"){for(let a=0;a<=4;a++)try{return await Me().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return _e(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=_t(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(_e(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&a<4){const c=250*Math.pow(2,a);await new Promise(p=>setTimeout(p,c));continue}return _e(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${a+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function xn({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 o=>{const a=await o.selectFrom("projects").selectAll().$if(!!e,c=>c.where("id","=",e)).$if(!!t,c=>c.where("slug","=",t)).executeTakeFirst();if(!a)return _e(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=a.metadata||{};if(!r&&!s)return i;const l=r?Pr(i,r):i;s&&await s(l,go(a));try{return await o.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",a.id).returningAll().executeTakeFirst()?l:(_e(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return _e(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(o){return _e(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}const Vu=()=>crypto.randomUUID();function Gu(e){const{id:t,projectId:r,analysisId:s,previousVersionId:o,analysis:a,metadata:i,data:l,...c}=e;return delete c.userScenarios,delete c.comments,"created_at"in c&&delete c.created_at,{...c,id:t??Vu(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:o}}async function qu(e){if(e.length===0)return[];const t=Me(),r=e.map(Gu);try{return(await t.insertInto("scenarios").values(r).onConflict(Ur(r[0],"id",["created_at"])).returningAll().execute()).map(Fi)}catch(s){return _e("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const Ku=()=>crypto.randomUUID();function Qu(e){const{id:t,commitId:r,branchId:s,...o}=e;return delete o.commit,delete o.branch,{...o,id:t??Ku(),commit_id:r,branch_id:s}}async function Ca(e){if(e.length===0)return[];const t=Me(),r=e.map(Qu);try{return(await t.insertInto("commit_branches").values(r).onConflict(Ur(r[0],"id",["created_at"])).returningAll().execute()).map(yo)}catch(s){return _e("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function Zu(e,t){const r=Me(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(Ur(s,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return _e("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:t}),null}}const Xu=()=>crypto.randomUUID();function ep(e,t){const{id:r,projectId:s,branchId:o,mergedBranchId:a,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:p,author:u,metadata:m,files:h,...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??Xu(),project_id:s??String(t),metadata:m?JSON.stringify(m):void 0,files:h?JSON.stringify(h):void 0,branch_id:o,merged_branch_id:a,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:p}}async function tp({projectId:e,commits:t}){const r=Me();try{const s=t.reduce((i,l)=>{const{author:c}=l;return c!=null&&c.username&&(c!=null&&c.avatarUrl)&&(i[c.username]=c.avatarUrl),i},{});for(const i in s)await Zu(i,s[i]);const o=t.map(i=>ep(i,e));return(await r.insertInto("commits").values(o).onConflict(Ur(o[0],"id",["created_at"])).returningAll().execute()).map(sn)}catch(s){return _e("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(o=>o.id).filter(Boolean)}),[]}}const _r=F.join(ao.homedir(),".codeyam","secrets.json"),jr=F.join(process.cwd(),".codeyam","secrets.json");async function Ut(){let e={};try{if(K.existsSync(jr)){const a=await ve.readFile(jr,"utf8");e=JSON.parse(a)}}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(K.existsSync(_r)){const a=await ve.readFile(_r,"utf8");e={...JSON.parse(a),...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 o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(t.GROQ_API_KEY=o),t}async function np(e,t=!0){const r=t?_r:jr,s=F.dirname(r);await ve.mkdir(s,{recursive:!0}),await ve.writeFile(r,JSON.stringify(e,null,2)),await ve.chmod(r,384)}function rp(e=!0){return e?_r:jr}async function Sa(){const e=await Ut(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function sp(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 Sd({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function op(e=!0){const t=await Sa();if(t.isValid)return t.secrets;const r=await sp(t.missing),o={...await Ut(),...r};await np(o,e);const a=rp(e);return console.log(Sr.green(`✓ Configuration saved to ${a}`)),(await Sa()).secrets}function ap(e){const t=F.resolve(e),r=F.parse(t).root;return t===r||t===F.resolve(ao.homedir())}function qi(e=process.cwd()){let t=F.resolve(e);const r=F.parse(t).root;for(;t!==r;){if(ap(t))return null;const s=F.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=F.dirname(t)}return null}let Ki=qi();function pe(){return Ki}function ip(e){Ki=e}function Qi(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const lp={"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>`};Qi(lp);const cp={"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>`};Qi(cp);function Ln(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const o=Array.isArray(e)?e:[],a=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?a[i]=Ln(o[i],l,r):a[i]=l}return a}const s={...e};for(const o in t)if(t[o]===null)s[o]=null;else if(Array.isArray(t[o])){const a=Array.isArray(e[o])?e[o]:[];s[o]=[];for(let i=0;i<t[o].length;i++){const l=t[o][i];typeof l=="object"&&l!==null?s[o][i]=Ln(a[i],l,r):s[o][i]=l}}else typeof t[o]=="object"&&t[o]!==null?s[o]=Ln(s[o]??{},t[o],r):s[o]=t[o];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function dp({projectId:e,commit:t,branch:r}){var l,c,p,u,m,h,f;let s;const o={commitId:t.id,branchId:r.id,active:!0},a=await Bu({projectId:e,commitId:t.id,includeBranches:!0});if(a&&a.length>0){s=(l=a.sort((g,x)=>{var v,b,w,S;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((S=(w=x.branch.metadata)==null?void 0:w.permanent)==null?void 0:S.order)??999)})[0])==null?void 0:l.branch,s&&((p=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:p.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(h=s.metadata)==null?void 0:h.permanent)==null?void 0:f.order)?s=r:o.active=!1);const y=a.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await Ca(y.map(g=>({...g,active:g.branchId===s.id})))}(a==null?void 0:a.find(y=>y.branchId===o.branchId))||await Ca([o])}function Wt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=pe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function ze(){const e=await op();process.env.SQLITE_PATH=Wt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function $e(e){await ze();const t=await Hu({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await Ji({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 up(e,t,r){await ze();const s=pe(),o=$u(`${e.slug}-local-${Date.now()}-${Math.random()}`),a=r.map(c=>{let p="";if(s)try{if(p=Ae(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!p)try{const u=Ae(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
|
|
30
|
+
`);p=`@@ -0,0 +1,${m.length} @@
|
|
31
|
+
${m.map(h=>`+${h}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:c,status:"modified",patch:p}}),i={sha:o,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${o}`,htmlUrl:`local://codeyam/${e.slug}/${o}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:a,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await tp({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await dp({projectId:e.id,commit:l[0],branch:t}),l[0]}async function cn(){await ze();const e=await et({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=t.get(p);(!u||c.createdAt&&u.createdAt&&c.createdAt>u.createdAt)&&t.set(p,c)}const r=[...t.values()],s=e.map(c=>c.sha),o=await zt({entityShas:s,excludeMetadata:!0}),a=new Map;if(o)for(const c of o)a.has(c.entitySha)||a.set(c.entitySha,[]),a.get(c.entitySha).push(c);const i=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=i.get(p)||[];u.push(c.sha),i.set(p,u)}return r.map(c=>{const p=a.get(c.sha)||[];if(p.length>0)return{...c,analyses:p};const u=`${c.name}::${c.filePath}`,m=i.get(u)||[];for(const h of m){if(h===c.sha)continue;const f=a.get(h);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Wr(e,t){await ze();const r=await zt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Hi({projectId:r[0].projectId,sha:e});if(s)for(const o of r)o.entity=s}return r||[]}async function Jr(e){if(await ze(),e.name&&e.projectId){const r=await zt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(a=>{const i=a.scenarios&&a.scenarios.length>0,l=!e.filePath||a.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((a,i)=>{const l=new Date(a.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const o=r.filter(a=>a.scenarios&&a.scenarios.length>0);if(o.length>0)return o.sort((a,i)=>{const l=new Date(a.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),o[0]}}const t=await zt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function Zi(e){await ze();const t=await zt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function an(e){await ze();const t=await Te();if(!t)return null;const{project:r}=await $e(t);return await Hi({projectId:r.id,sha:e})}async function Xi(e){var s,o,a,i,l,c,p,u;await ze();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const h of m){if(!h.filePath||!h.name)continue;const f=h.resolvedFilePath??h.filePath,y=h.resolvedName??h.name;let g=await et({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&h.resolvedIsDefault&&(g=await et({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await zt({entityShas:[x.sha],limit:1});let b,w,S;if(v&&v.length>0&&v[0].scenarios){const E=v[0],k=E.scenarios||[],N=k.length,C=k.find(T=>{var P,_;return(_=(P=T.metadata)==null?void 0:P.screenshotPaths)==null?void 0:_[0]});C&&(b=(a=(o=C.metadata)==null?void 0:o.screenshotPaths)==null?void 0:a[0],w=C.name),S={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||E.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:E.createdAt?new Date(E.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else S={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:w,analysisStatus:S})}}}if((l=e.metadata)!=null&&l.importedBy){const m=[];for(const h in e.metadata.importedBy)for(const f in e.metadata.importedBy[h]){const y=e.metadata.importedBy[h][f];y.shas&&m.push(...y.shas)}if(m.length>0){const h=await et({projectId:e.projectId,shas:m});if(h)for(const f of h){const y=await zt({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],w=b.scenarios||[],S=w.length,E=w.find(N=>{var C,A;return(A=(C=N.metadata)==null?void 0:C.screenshotPaths)==null?void 0:A[0]});E&&(g=(p=(c=E.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0],x=E.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:S,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 Te(){try{const e=pe();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await we.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Nn(){await ze();try{const e=await Te();if(!e)return null;const{project:t,branch:r}=await $e(e),s=await Ar({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 Hr(){try{const e=pe();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await we.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function el(e){try{const t=pe();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ee.join(t,e.filePath);return await we.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function tl(e){try{const t=pe();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),o=(await we.stat(r)).mtime.getTime(),a=e.updatedAt||e.createdAt;if(!a)return!1;const i=new Date(a).getTime();return o>i+1e3}catch{return!1}}async function nl(e){if(await ze(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await et({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await zt({entityShas:r}),o=new Map;if(s)for(const i of s)o.has(i.entitySha)||o.set(i.entitySha,[]),o.get(i.entitySha).push(i);for(const[i,l]of o.entries())l.sort((c,p)=>{const u=new Date(c.createdAt||0).getTime();return new Date(p.createdAt||0).getTime()-u});const a=t.map(i=>({...i,analyses:o.get(i.sha)||[]}));return a.sort((i,l)=>{var u,m;const c=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",p=((m=l.analyses[0])==null?void 0:m.createdAt)||l.createdAt||"";return new Date(p).getTime()-new Date(c).getTime()}),a}async function rl(e){try{const t=pe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await we.readFile(r,"utf8"),o=JSON.parse(s),a={...o,...e},i=JSON.stringify(a,null,2);if(await we.writeFile(r,i,"utf8"),o.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await xn({projectSlug:o.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const pp=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:cn,getAnalysesForEntity:Wr,getAnalysisForExactEntitySha:Zi,getCurrentCommit:Nn,getEntityBySha:an,getEntityCodeFromFilesystem:el,getEntityHistory:nl,getLatestAnalysisForEntity:Jr,getProjectConfig:Hr,getProjectSlug:Te,getRelatedEntities:Xi,hasFileBeenModifiedSinceEntity:tl,requireBranchAndProject:$e,updateProjectConfig:rl},Symbol.toStringTag,{value:"Module"})),sl="secrets.json";function ol(e){return ee.join(e,".codeyam",sl)}function al(){return ee.join(Os.homedir(),".codeyam",sl)}async function Vr(e){let t={};try{const r=al(),s=await we.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=ol(e),s=await we.readFile(r,"utf-8"),o=JSON.parse(s);t={...t,...o}}catch{}return t}async function mp(e,t,r=!0){const s=r?al():ol(e),o=ee.dirname(s);await we.mkdir(o,{recursive:!0}),await we.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}async function hp(e){const t=await Vr(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 fp=3;let $n=0;async function sr(e){if(!e||e.length===0)return[];if($n>=fp)return console.warn(`[Loader] Circuit breaker open (${$n} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const o=setTimeout(()=>{s||(s=!0,$n++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);et({shas:e,excludeMetadata:!0}).then(a=>{s||(s=!0,clearTimeout(o),$n=0,r(a||[]))}).catch(()=>{s||(s=!0,clearTimeout(o),$n++,r([]))})})}function gp({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(Ot(t))try{if(gd(t).length>0)return!1;ps(t,{recursive:!0})}catch{return!1}try{Ae(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const o of r)if(o.includes("*"))try{Ae(`rm -rf "${xa(t,o)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const a=xa(t,o);Ot(a)&&ps(a,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(Ot(t))try{ps(t,{recursive:!0})}catch{}return!1}}async function yp({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:o=!1,extraArgs:a=[]}){const i=Date.now();if(!s&&a.length===0&&gp({sourcePath:e,destinationPath:t,excludes:r,silent:o})){if(!o){const c=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${c}s]`)}return}return new Promise((l,c)=>{const p=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...a);for(const f of r)m.push(`--exclude=${f}`);m.push(p,u);const h=At("rsync",m);h.on("exit",f=>{if(f===0){if(!o){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}l()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:m},null,2)),c(new Error(`rsync failed with exit code ${f}`))}),h.on("error",f=>{o||console.log("Error occurred:",f),c(f)})})}const xp=co(lo);async function bp(e){return new Promise(t=>setTimeout(t,e))}function vp(e){try{return process.kill(e,0),!0}catch{return!1}}async function il(e){try{const{stdout:t}=await xp(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
+
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),s=[...r];for(const o of r){const a=await il(o);s.push(...a)}return s}catch{return[]}}function ka(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function wp(e,t,r){const s=await il(e);for(const o of s.reverse())await ka(o,t,r);await ka(e,t,r)}async function Wn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function o(a,i){await wp(e,a,t);for(let l=0;l<i;l++)if(await bp(1e3),s+=1e3,!await vp(e))return t(`Process tree ${e} successfully killed with ${a} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${a}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let a=0;a<r;a++)if(await o("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function Np(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ld(),createdAt:t}}Ad.config({quiet:!0});var ll=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ll||{});class Cp extends Pd{constructor(){super(...arguments),this.processes=new Map}register(t){const r=_d(),{process:s,type:o,name:a,metadata:i,parentId:l}=t,c={id:r,type:o,name:a,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:c,process:s}),l){const m=this.processes.get(l);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const p=(m,h)=>{this.handleProcessExit(r,m,h)},u=m=>{this.handleProcessError(r,m)};return s.on("exit",p),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",p),s.removeListener("error",u)},this.emit("processStarted",c),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:o,process:a}=s;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(r.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(l=>this.shutdown(l,r))),a.pid)try{await Wn(a.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=a.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(o=>this.shutdown(o.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[o,a]of this.processes.entries()){const{info:i}=a;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=a.process.__cleanup;l&&l(),this.processes.delete(o)}}}handleProcessExit(t,r,s){const o=this.processes.get(t);if(!o)return;const{info:a}=o;a.endedAt=Date.now(),a.exitCode=r,a.signal=s,r===0?a.state="completed":s?a.state="killed":a.state="failed",this.emit("processExited",a)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:r.message},this.emit("processExited",o)}}let bs=null;function Sp(){return bs||(bs=new Cp),bs}const kp={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Ep({command:e,args:t,workingDir:r,outputOptions:s=kp,processName:o,env:a}){const i={...process.env,...a||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},l=At(e,t,{cwd:r,env:i});return Sp().register({process:l,type:ll.Other,name:o,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const y=ee.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},h=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
+
`).map(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
|
|
36
|
+
`)};l.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&m(g+`
|
|
37
|
+
`),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&m(g+`
|
|
38
|
+
`),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){u(f)})}),process:l}}function Ap(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 Pp({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const o=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
+
`);K.writeFileSync(`${e}/.env`,o);const a=Ap(r);return Ep({command:"node",args:["--enable-source-maps","./dist/project/start.js",...a],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const _p="/tmp/codeyam/local-dev";function cl(e){return F.join(_p,e)}function dl(e){return F.join(cl(e),"codeyam")}function mt(e){return F.join(cl(e),"project")}function Gr(e){return F.join(dl(e),"log.txt")}const jp=[".sync-metadata.json","__codeyamMocks__"];async function Mp(e,t={}){const{port:r,silent:s=!0}=t,o=mt(e);if(r)try{Ae(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Ae(`lsof +D "${o}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(a=>setTimeout(a,500))}async function Tp(e,t={}){const{killProcesses:r=!0,port:s,silent:o=!0}=t,a=mt(e),i=[],l=[];if(!K.existsSync(a))return{removed:i,errors:l};r&&await Mp(e,{port:s,silent:o});for(const c of jp){const p=F.join(a,c);if(K.existsSync(p))try{(await ve.stat(p)).isDirectory()?await ve.rm(p,{recursive:!0,force:!0}):await ve.unlink(p),i.push(c)}catch(u){l.push(`${c}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const $p=F.dirname(Lr(import.meta.url));function Rp(e){let t=e;for(;t!==F.dirname(t);){const r=F.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=F.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function qr(){const e=Rp($p);return F.join(e,"analyzer-template")}function Cn(e){return dl(e)}function Ip(){const e=qr();return K.existsSync(F.join(e,".finalized"))}async function Ea(e){const t=qr(),r=Cn(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await ve.mkdir(F.dirname(r),{recursive:!0}),await yp({sourcePath:t,destinationPath:r,silent:!0})}function Sn(e,t,r,s){const o=Cn(e);if(!K.existsSync(o))throw new Error(`Analyzer not found at ${o}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const a=void 0;return Pp({absoluteCodeyamRootPath:o,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:a,stderrToConsole:!1,stderrToFile:!0,stderrCallback:a}})}function Dp(e){const t=qr(),r=Cn(e),s=F.join(t,".build-info.json"),o=F.join(r,".build-info.json");if(!K.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const a=JSON.parse(K.readFileSync(s,"utf8")),i=JSON.parse(K.readFileSync(o,"utf8"));return a.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${a.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(a){return{isFresh:!1,reason:`Error reading build markers: ${a.message}`}}}async function Qn(e,t){const r=Cn(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await Ea(e);return}const s=Dp(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Ea(e))}async function xo(e){await Tp(e,{killProcesses:!1})}const Op=F.dirname(Lr(import.meta.url));function Kr(){let e=Op;for(;e!==F.dirname(e);){const t=F.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=F.dirname(e)}return null}function gn(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Lp(){const e=Kr();if(e){const t=[F.join(e,"src/webserver/build-info.json"),F.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=gn(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function Fp(){const e=Kr();if(e){const t=F.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const bo=Lp(),vs=Fp();function vo(){if(vs!=="unknown"&&vs!=="0.1.0")return vs;const e=Kr();if(e)for(const t of[F.join(e,"src/webserver/build-info.json"),F.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=gn(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function ul(e){const t=Kr();let r=null;if(t){const c=[F.join(t,"src/webserver/build-info.json"),F.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const p of c)if(r=gn(p),r)break}const s=qr(),o=F.join(s,".build-info.json"),a=gn(o);let i=null;if(e){const c=Cn(e),p=F.join(c,".build-info.json");i=gn(p)}let l=!1;return a&&i?l=a.buildTime>i.buildTime:a&&!i&&e&&(l=!0),{cliVersion:bo,webserverVersion:r,templateVersion:a,cachedAnalyzerVersion:i,isCacheStale:l}}function Qr(e){const t=Cn(e),r=F.join(t,".build-info.json"),s=gn(r);return(s==null?void 0:s.version)??null}function pl(){const e=pe();return e?F.join(e,".codeyam","server.json"):null}function ml(){const e=pl();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function zp(){const e=pl();if(e)try{K.unlinkSync(e)}catch{}}const Bp="/assets/globals-BkWJ_UNc.css";function Aa({text:e,subtext:t,linkText:r,linkTo:s}){const[o,a]=M(!1);return o?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(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:()=>a(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Yp({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:d("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),d("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Up({serverVersion:e}){const[t,r]=M("stale"),[s,o]=M(null),a=async()=>{r("restarting"),o(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const c=30,p=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?setTimeout(()=>void u(),p):(o("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){o(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),d("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&d(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"&&d(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 a(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&d("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[d("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function Mt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:o=2e3,ariaLabel:a,icon:i=!1,iconSize:l=14}){const[c,p]=M(!1),u=ae(()=>{navigator.clipboard.writeText(e).then(()=>{p(!0),setTimeout(()=>p(!1),o)}).catch(m=>{console.error("Failed to copy:",m)})},[e,o]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:c,"aria-label":a||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(ft,{size:l,className:"text-green-500"}):n(St,{size:l}):c?r:t})}function Wp({currentVersion:e,latestVersion:t}){const[r,s]=M(!1);if(r)return null;const o="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),d("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),d("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:o}),n(Mt,{content:o,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Rn=null,or=0;const Jp=3600*1e3;function Hp(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let o=0;o<Math.max(r.length,s.length);o++){const a=r[o]??0,i=s[o]??0;if(isNaN(a)||isNaN(i))return!1;if(a>i)return!0;if(a<i)return!1}return!1}async function Vp(){const e=vo();if(Rn&&Date.now()-or<Jp)return Rn;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Rn=l,or=Date.now(),l}const a=(await s.json()).version;if(!a){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Rn=l,or=Date.now(),l}const i={updateAvailable:Hp(a,e),latestVersion:a,currentVersion:e};return Rn=i,or=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Mr(e){return F.join(e,".codeyam","queue.json")}function Fn(e){const t=Mr(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Gp(e,t){const r=Mr(e),s=F.dirname(r);K.existsSync(s)||K.mkdirSync(s,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}const Ir=class Ir extends Fr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=fe.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Ir.IGNORED_DIRS.some(o=>r.includes(o+"/")||r.includes(o+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!fe.existsSync(r)){fe.existsSync(s)&&(fe.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const o=ee.dirname(s);fe.existsSync(o)||fe.mkdirSync(o,{recursive:!0}),fe.copyFileSync(r,s);const a=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:a,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(o){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,o);const a={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",a)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Ir.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Fs=Ir,qp=class extends Fr{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 zs="__codeyam_dev_mode_event_emitter__";globalThis[zs]||(globalThis[zs]=new qp);const Pa=globalThis[zs],Bs=new Map;async function Kp(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Qp(e,t,r);else if(e.type==="baseline")await Zp(e,t,r);else if(e.type==="recapture")await Xp(e,t,r);else if(e.type==="capture-only")await em(e,t,r);else if(e.type==="debug-setup")await tm(e,t,r);else if(e.type==="interactive-start")await nm(e,t,r);else if(e.type==="interactive-stop")await rm(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 Qp(e,t,r){var g,x,v,b;const{projectSlug:s,commitSha:o,entityShas:a}=e;if(!o)throw new Error("Analysis job missing commitSha");const i=a||[],{project:l}=await $e(s);await xo(s),await Qn(s,{update:w=>console.log(`[Queue] ${w}`)});const c=Qr(s),p={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...c?{ANALYZER_VERSION:c}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=l.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,h={packageManager:((v=l.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:mt(s),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=Sn(s,p,h),y=w=>{try{return process.kill(w,0),!0}catch{return!1}};await Lt({commitSha:o,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((S,E)=>setTimeout(()=>E(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,w]),await Lt({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Lt({commitSha:o,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(S=>setTimeout(S,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Wn(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 Wn(f.process.pid,()=>{})}catch{}try{await Lt({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:w instanceof Error?w.message:String(w)}}),r==null||r.notifyChange("commit")}catch(S){console.error("[Queue] Failed to update commit metadata after job failure:",S)}throw w}}async function Zp(e,t,r){var h,f,y;const{projectSlug:s,commitSha:o}=e;if(!o)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:a}=await $e(s);await xo(s),await Qn(s,{update:g=>console.log(`[Queue] ${g}`)});const i=Qr(s),l={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(h=a.metadata)==null?void 0:h.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const p={packageManager:((y=a.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:mt(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},u=Sn(s,l,p),m=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Lt({commitSha:o,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 Lt({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await Wn(u.process.pid,()=>{})}catch{}}}async function Xp(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:o,scenarioId:a,defaultWidth:i}=e;if(!o)throw new Error("Recapture job missing analysisId");const l=await jt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:v}=await import("./index-CbF6h3dj.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let S={};w!=null&&w.metadata&&(typeof w.metadata=="string"?S=JSON.parse(w.metadata):S=w.metadata),S.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(S)}).where("sha","=",l.entitySha).execute()}await wn(o,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!a||b.name===a)&&(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:c}=await $e(s);await Qn(s,{update:v=>console.log(`[Queue] ${v}`)});const p=Qr(s),u={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,...a?{SCENARIO_IDS:a}:{},...p?{ANALYZER_VERSION:p}:{}},m={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:mt(s),port:void 0,noServer:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??He.Next,orchestrateCapture:"local-sequential"},h=Sn(s,u,m);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function em(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:o,scenarioId:a,defaultWidth:i}=e;if(!o)throw new Error("Capture-only job missing analysisId");const l=await jt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:v}=await import("./index-CbF6h3dj.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let S={};w!=null&&w.metadata&&(typeof w.metadata=="string"?S=JSON.parse(w.metadata):S=w.metadata),S.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(S)}).where("sha","=",l.entitySha).execute()}await wn(o,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!a||b.name===a)&&(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:c}=await $e(s);await Qn(s,{update:v=>console.log(`[Queue] ${v}`)});const p=Qr(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:o,...a?{SCENARIO_IDS:a}:{},...p?{ANALYZER_VERSION:p}:{}},m={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:mt(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??He.Next,orchestrateCapture:"local-sequential"},h=Sn(s,u,m);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function tm(e,t,r){var h,f,y,g;const{projectSlug:s,analysisId:o,scenarioId:a}=e;if(!o)throw new Error("Debug setup job missing analysisId");const i=await jt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await $e(s);await xo(s),await Qn(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,PREP_ONLY:"true"};a&&(c.SCENARIO_IDS=a);const p={packageManager:((h=l.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:mt(s),port:void 0,noServer:!1,framework:((g=(y=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||He.Next},m=await Sn(s,c,p).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function nm(e,t,r){var x,v,b,w;const{projectSlug:s,analysisId:o,scenarioId:a}=e;if(!o)throw new Error("Interactive start job missing analysisId");const i=await jt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:l}=await $e(s),c={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,INTERACTIVE_MODE:"true"};a&&(c.SCENARIO_IDS=a);const p=mt(s),u=ee.join(p,".next","dev","lock");if(fe.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const S=Ae(`pgrep -f ${JSON.stringify(p)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(S)for(const E of S.split(`
|
|
40
|
+
`).filter(Boolean))try{process.kill(parseInt(E,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${E}`)}catch{}}catch{}try{fe.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const m=fe.existsSync(p)&&fe.existsSync(ee.join(p,"package.json")),h={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:p,port:void 0,noServer:!1,fast:m,framework:((w=(b=(v=l.metadata)==null?void 0:v.webapps)==null?void 0:b[0])==null?void 0:w.framework)||He.Next};await wn(o,S=>{S.readyToBeCaptured=!0});const f=Sn(s,c,h);await Gi(o,S=>{S.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${o}, PID: ${f.process.pid}`);const y=mt(s),g=new Fs({projectRootPath:t,tmpProjectPath:y});g.on("sync",S=>{S.type==="file-synced"?Pa.emitFileSynced(S.fileName,S.filePath):S.type==="error"&&Pa.emitError(S.fileName,S.filePath)}),g.start(),Bs.set(o,g),console.log(`[Queue] File sync watcher started for analysis ${o}`)}async function rm(e,t,r){var p;const{projectSlug:s,analysisId:o}=e;if(!o)throw new Error("Interactive stop job missing analysisId");const a=await jt({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${o} not found`);const i=(p=a.metadata)==null?void 0:p.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${o}`);return}const l=Bs.get(o);l&&(l.stop(),Bs.delete(o),console.log(`[Queue] File sync watcher stopped for analysis ${o}`));const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${o}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Wn(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${c}:`,u),u}finally{await Gi(o,u=>{u.interactiveMode=null})}}class sm{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=Fn(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||io(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const o=new Promise((a,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):a()})});return this.state.paused||this.processNext().catch(a=>{console.error("[Queue] ERROR in processNext():",a)}),{jobId:r,completion:o}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(o=>o.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const o=this.completionCallbacks.get(t);o&&(setImmediate(()=>o(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const o=r==="up"?s-1:s+1;if(o<0||o>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const a=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[o],this.state.jobs[o]=a,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${o})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Kp(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(){Gp(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class om{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Mr(this.projectRoot);if(!K.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=Mr(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.watch(r,(s,o)=>{o==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=K.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 am{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Fn(r)}start(){this.cachedState=Fn(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 om(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const o=new Promise((i,l)=>{r=i,s=l}),a=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:a,completion:o}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Fn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Fn(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 im(e){const t=F.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function lm(e){try{return process.kill(e,0),!0}catch{return!1}}async function cm(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 dm(e){const t=im(e);return!t||!lm(t.pid)||!await cm(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class um extends Fr{constructor(){super();Mn(this,"watcher",null);Mn(this,"dbPath",null);Mn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=Wt();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",o=>{const a=Date.now(),i=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${o}`),console.log(`[dbNotifier] Timestamp: ${i} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:a})}).on("error",o=>{console.error("Database watcher error:",o),this.emit("error",o)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),o=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${o} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const it=new um;let nn=null,zn=null;async function pm(){if(!nn){if(zn){await zn;return}zn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||qi()||process.cwd();if(ip(e),console.log(`[GlobalQueue] Project root: ${e}`),await ze(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),o=JSON.parse(await fe.promises.readFile(r,"utf8")).projectSlug;o&&(await xn({projectSlug:o,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await dm(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new am(t,e,()=>{it.notifyChange("unknown")});await r.start(),nn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new sm(e,it);await r.start(),nn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await zn}}async function Tt(){return nn||await pm(),nn}function mm(){return nn||(zn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const hm=()=>[{rel:"stylesheet",href:Bp},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],fm={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:vo()};async function gm({request:e,context:t}){var r,s,o,a,i,l,c,p,u,m,h;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=pe()||process.cwd(),[x,v,b]=await Promise.all([Te(),Vr(g),Vp().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:w,branch:S}=await $e(x);y();const E=await Ar({projectId:w.id,branchId:S.id,limit:20,skipRelations:!0});y();const k=E.length>0?E[0]:null,N=t.analysisQueue||mm(),C=N==null?void 0:N.getState();y();const A=await Promise.all(((C==null?void 0:C.jobs)||[]).map(async G=>{var le;const X=await sr(G.entityShas||[]);return X.length===0&&((le=G.entityShas)!=null&&le.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",G.id),{...G,entities:X}}));let T=null;if(C!=null&&C.currentlyExecuting){const G=C.currentlyExecuting,X=await sr(G.entityShas||[]);X.length===0&&((r=G.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",G.id),T={...G,entities:X}}const P=T?A.filter(G=>G.id!==T.id):A;let _=((o=(s=k==null?void 0:k.metadata)==null?void 0:s.currentRun)==null?void 0:o.currentEntityShas)||[];if(_.length===0){const G=((a=k==null?void 0:k.metadata)==null?void 0:a.historicalRuns)||[];if(G.length>0){const le=[...G].sort((xe,oe)=>{const me=xe.archivedAt||xe.createdAt||"";return(oe.archivedAt||oe.createdAt||"").localeCompare(me)})[0];if(le){const xe=le.analysisCompletedAt||le.createdAt;if(xe){const oe=new Date(xe).getTime(),Ce=Date.now()-1440*60*1e3;oe>Ce&&(_=le.currentEntityShas||[])}}}}const $=await sr(_),I=[];v.ANTHROPIC_API_KEY&&I.push("ANTHROPIC_API_KEY"),v.GROQ_API_KEY&&I.push("GROQ_API_KEY"),v.OPENAI_API_KEY&&I.push("OPENAI_API_KEY"),v.OPENROUTER_API_KEY&&I.push("OPENROUTER_API_KEY"),y();const R=[];for(const G of E){const X=((i=G.metadata)==null?void 0:i.historicalRuns)||[];for(const le of X)R.push(le)}R.sort((G,X)=>{const le=G.archivedAt||G.analysisCompletedAt||G.createdAt||"";return(X.archivedAt||X.analysisCompletedAt||X.createdAt||"").localeCompare(le)});const Y=new Set(((l=T==null?void 0:T.entities)==null?void 0:l.map(G=>G.sha))||[]),W=R.filter(G=>!(G.currentEntityShas||[]).some(le=>Y.has(le))).slice(0,3),B=new Set;for(const G of W)for(const X of G.currentEntityShas||[])B.add(X);const D=await sr(Array.from(B)),O=new Map;for(const G of D)O.set(G.sha,G);const j=W.map(G=>({...G,entities:(G.currentEntityShas||[]).map(X=>O.get(X)).filter(X=>X!=null)})),q=ml(),V=(q==null?void 0:q.cliVersion)??"unknown",U=V!=="unknown"&&V!==bo,Z=((p=(c=w.metadata)==null?void 0:c.labs)==null?void 0:p.simulations)??!1,z=Z?Ip():!1,L=((u=w.metadata)==null?void 0:u.editorMode)??!1,J={currentRun:(m=k==null?void 0:k.metadata)==null?void 0:m.currentRun,projectSlug:x,currentEntities:$,availableAPIKeys:I,queuedJobCount:P.length,queueJobs:P,currentlyExecuting:T,historicalRuns:j,isServerOutOfDate:U,serverVersion:V,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((h=w.metadata)==null?void 0:h.labs)??null,simulationsEnabled:Z,isSimulationsReady:z,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:L,displayVersion:vo()};return Q(J)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),Q(fm)}}function ym(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:o,queueJobs:a,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:p,npmUpdate:u,labs:m,simulationsEnabled:h,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=Ve(),{toasts:v,closeToast:b}=ho(),w=ht(),S=be(w),E=Dr();te(()=>{S.current=w},[w]);const k=E.pathname.startsWith("/entity/")&&E.pathname.includes("/edit/")||E.pathname.startsWith("/dev/")||E.pathname.startsWith("/editor"),N=E.pathname.includes("/fullscreen")||E.pathname.startsWith("/editor");return te(()=>{const C=new EventSource("/api/events");let A=null,T=0;const P=2e3;return C.addEventListener("message",_=>{const $=JSON.parse(_.data);if($.type==="queue")S.current.revalidate(),T=Date.now();else if($.type==="db-change"||$.type==="unknown"){const I=Date.now(),R=I-T;R<P?(A&&clearTimeout(A),A=setTimeout(()=>{S.current.revalidate(),T=Date.now(),A=null},P-R)):(S.current.revalidate(),T=I)}}),C.addEventListener("error",_=>{console.error("SSE connection error:",_)}),()=>{A&&clearTimeout(A),C.close()}},[]),d(ue,{children:[d("div",{className:`min-h-screen ${k?"":"grid"} bg-cygray-10`,style:k?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!k&&n(qd,{labs:m,isAdmin:y,editorMode:g}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(Up,{serverVersion:p}),u&&u.currentVersion&&n(Wp,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),h&&s.length===0&&n(Aa,{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"}),h&&!f&&n(Aa,{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(Mc,{})}),n(Yp,{version:x})]})]}),n(Zd,{toasts:v,onClose:b}),!N&&h&&n(Xd,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:a,currentlyExecuting:i,historicalRuns:l})]})}const xm=We(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Ac,{}),n(Pc,{})]}),d("body",{children:[n(Kd,{children:n(Vd,{children:n(ym,{})})}),n(_c,{}),n(jc,{})]})]})}),bm=Object.freeze(Object.defineProperty({__proto__:null,default:xm,links:hm,loader:gm},Symbol.toStringTag,{value:"Module"}));function ar(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function dn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,enabled:a=!0,refreshTrigger:i=0}){const l=Oe(),[c,p]=M(null),[u,m]=M(!1),[h,f]=M(!1),[y,g]=M(!1),x=be(!1),v=be(null),b=be(null),w=be(null),[S,E]=M(0),[k,N]=M(0),C=be(null),A=be(!1),{interactiveUrl:T,resetLogs:P}=Pt(o,a),_=be(t),$=be(i);te(()=>{$.current!==i&&($.current=i,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),E(0),N(R=>R+1),A.current=!1,C.current&&(clearTimeout(C.current),C.current=null)))},[i,c]),te(()=>{if(_.current!==t&&(_.current=t,v.current&&b.current&&r)){let R=v.current;if(w.current&&s){const W=ar(w.current),B=ar(s);W!==B&&(R=R.replace(W,B),w.current=s)}const Y=ar(b.current),H=ar(r);R=R.replace(Y,H),b.current=r,p(R),f(!0),g(!1),E(0),N(W=>W+1),A.current=!1,C.current&&(clearTimeout(C.current),C.current=null);return}},[t,r,s]),te(()=>{if(T){const R=T+"?width=600px";v.current=R,r&&(b.current=r),s&&(w.current=s),p(R),m(!1),f(!0)}},[T]),te(()=>{const R=Y=>{Y.data.type==="codeyam-resize"&&(A.current||(A.current=!0,C.current&&(clearTimeout(C.current),C.current=null),E(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",R),()=>window.removeEventListener("message",R)},[]);const I=()=>{A.current=!1,C.current&&clearTimeout(C.current);const R=300*Math.pow(2,S);C.current=setTimeout(()=>{A.current||(S<2?(E(Y=>Y+1),N(Y=>Y+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},R)};return te(()=>{a&&!x.current&&t&&e&&(x.current=!0,m(!0),g(!1),p(null),(async()=>{if(o)try{await fetch(`/api/logs/${o}`,{method:"DELETE"})}catch(Y){console.error("[useInteractiveMode] Failed to clear log file:",Y)}P(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[a,t,e,P,o]),te(()=>{const R=e,Y=()=>{if(x.current&&R){const W=new URLSearchParams({action:"stop",analysisId:R});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const B=navigator.sendBeacon("/api/interactive-mode",W);console.log("[useInteractiveMode] sendBeacon result:",B),B||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,keepalive:!0}).catch(D=>console.error("Failed to stop interactive mode:",D)))}},H=()=>{Y()};return window.addEventListener("beforeunload",H),()=>{window.removeEventListener("beforeunload",H),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:R}),Y()}},[e]),{interactiveServerUrl:c,isStarting:u,isLoading:h,showIframe:y,iframeKey:k,onIframeLoad:I}}const ir=10,vm=1024;function wo({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:o,hideLabel:a=!1,lightMode:i=!1}){const[l,c]=M(null),p=be(null),u=ne(()=>[...s].sort((b,w)=>b.width-w.width),[s]),{fittingPresets:m,overflowPresets:h}=ne(()=>{const b=[],w=[];for(const S of u)S.width<=vm?b.push(S):w.push(S);return w.sort((S,E)=>E.width-S.width),{fittingPresets:b,overflowPresets:w}},[u]),f=ae(b=>{if(!p.current)return null;const w=p.current.getBoundingClientRect(),S=b-w.left,E=w.width,k=E/2,C=(m.length>0?m[m.length-1].width:0)/2,A=k-C,T=k+C,P=h.length>0?(h.length-1)*ir:0;if(h.length>0){if(S<A){if(S<=P){const $=Math.min(Math.floor(S/ir),h.length-1);return h[$]}return h[h.length-1]}if(S>T){const $=E-S;if($<=P){const I=Math.min(Math.floor($/ir),h.length-1);return h[I]}return h[h.length-1]}}const _=Math.abs(S-k);for(let $=m.length-1;$>=0;$--){const I=m[$],R=m[$-1],Y=I.width/2,H=R?R.width/2:0;if(_<=Y&&_>=H)return I}return m[0]||h[h.length-1]||null},[m,h]),y=ae(b=>{const w=f(b.clientX);c(w),o==null||o(w)},[f,o]),g=ae(()=>{c(null),o==null||o(null)},[o]),x=ae(b=>{const w=f(b.clientX);w&&r(w)},[f,r]),v=l||{name:t,width:e};return d("div",{ref:p,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map(b=>{const w=b.width===e,S=(l==null?void 0:l.name)===b.name,E=b.width/2;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||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:{left:`calc(50% + ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||S?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:h.map((b,w)=>{const S=w*ir,E=b.width===e,k=(l==null?void 0:l.name)===b.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${S}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||k?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:`${S}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||k?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!a&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:d("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[v.name," - ",v.width,"px"]})})]})}function Zr({width:e,height:t,onSave:r,onCancel:s}){const[o,a]=M(""),[i,l]=M(""),c=()=>{const u=o.trim();if(!u){l("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),d("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:o,onChange:u=>{a(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&o.trim()&&c(),u.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:c,disabled:!o.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] 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 Xr(e){const[t,r]=M([]),s=e?`codeyam-custom-sizes-${e}`:null;te(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const c=JSON.parse(l);Array.isArray(c)&&r(c)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const o=ae(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(c){console.error("[useCustomSizes] Failed to save custom sizes:",c)}},[s]),a=ae((l,c,p)=>{r(u=>{const m=u.findIndex(y=>y.name===l),h={name:l,width:c,height:p};let f;return m>=0?(f=[...u],f[m]=h):f=[...u,h],o(f),f})},[o]),i=ae(l=>{r(c=>{const p=c.filter(u=>u.name!==l);return o(p),p})},[o]);return{customSizes:t,addCustomSize:a,removeCustomSize:i}}function Bt(){return d("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 _a=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],wm=80;function bn(){const[e,t]=M(0);return te(()=>{const r=setInterval(()=>{t(s=>(s+1)%_a.length)},wm);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:_a[e]})}async function Nm({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await an(t);if(!s)throw Q("Entity not found",{status:404});const o=await Jr(s),a=((l=o==null?void 0:o.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!a)throw Q("Scenario not found",{status:404});const i=await Te();return Q({entity:s,scenario:a,analysis:o,projectSlug:i})}const ws=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Cm=We(function(){const{entity:t,scenario:r,analysis:s,projectSlug:o}=Ve(),a=Et(),[i]=vn(),[l,c]=M(null),[p,u]=M(1440),[m,h]=M({name:"Desktop",width:1440,height:900}),[f,y]=M(!1),[g,x]=M(null),{customSizes:v,addCustomSize:b}=Xr(o),w=ne(()=>[...ws,...v],[v]),{interactiveServerUrl:S,isStarting:E,isLoading:k,showIframe:N,iframeKey:C,onIframeLoad:A}=dn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),{lastLine:T}=Pt(o,E||k),P=()=>{a(`/entity/${t.sha}`)},_=(V,U)=>{u(V);const Z=w.find(L=>L.width===V&&L.height===U);c(Z||null),h({name:(Z==null?void 0:Z.name)||"Custom",width:V,height:U})},$=V=>{c(V),u(V.width),h({name:V.name,width:V.width,height:V.height})},I=V=>{b(V,m.width,m.height??900),y(!1),h(U=>({...U,name:V}))},R=((s==null?void 0:s.scenarios)||[]).filter(V=>{var U;return!((U=V.metadata)!=null&&U.sameAsDefault)}),Y=R.findIndex(V=>V.id===(r==null?void 0:r.id)),H=Y+1,W=R.length,B=Y>0,D=Y<R.length-1,O=()=>{if(B){const V=R[Y-1],U=encodeURIComponent(`/entity/${t.sha}/scenarios/${V.id}/fullscreen`);a(`/entity/${t.sha}/scenarios/${V.id}/fullscreen?from=${U}`)}},j=()=>{if(D){const V=R[Y+1],U=encodeURIComponent(`/entity/${t.sha}/scenarios/${V.id}/fullscreen`);a(`/entity/${t.sha}/scenarios/${V.id}/fullscreen?from=${U}`)}},q=E||k||!N;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Br,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:O,disabled:!B,className:`${B?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[H,"/",W]}),n("button",{onClick:j,disabled:!D,className:`${D?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:P,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ws[ws.length-1].width}px`,width:"100%"},children:n(wo,{currentViewportWidth:p,currentPresetName:m.name,onDevicePresetClick:$,devicePresets:w,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:m.name,onChange:V=>{const U=w.find(Z=>Z.name===V.target.value);U&&$(U)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[w.map(V=>n("option",{value:V.name,children:V.name},V.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:V=>{const U=parseInt(V.target.value,10);!isNaN(U)&&U>0&&_(U,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:S?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[q&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),T&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),T]})]})]})}),n("iframe",{src:S,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:A,style:{opacity:N?1:0}},C)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),T&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),T]})]})]})}),f&&n(Zr,{width:m.width,height:m.height??900,onSave:I,onCancel:()=>y(!1)})]})}),Sm=Object.freeze(Object.defineProperty({__proto__:null,default:Cm,loader:Nm},Symbol.toStringTag,{value:"Module"}));function hl({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:o,notificationsEnabled:a,onToggleNotifications:i}){const[l,c]=M(null),p=be(null);te(()=>{if(!r)return;const f=new EventSource("/api/dev-mode-events");return f.onmessage=y=>{try{const g=JSON.parse(y.data);g.type==="file-synced"&&(c(g.fileName),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{f.close(),p.current&&clearTimeout(p.current)}},[r]);let u;s?u="error":t?u="starting":e?u="running":u="stopped";const m={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},h={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${m[u]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:h[u]})]}),(u==="stopped"||u==="error")&&o&&n("button",{onClick:o,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&d(ue,{children:[d("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&n("button",{onClick:i,className:`text-[11px] rounded transition-colors cursor-pointer ${a?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:a?"Click to turn off notifications":"Click to get notified when Claude finishes",children:a?"Notifications On":"Notifications Off"})]})}async function km(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),o=new s;return o.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),o.dispose(),ja(e).then(a=>{a||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(o),{type:"webgl",dispose:()=>o.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await ja(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function ja(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}const Em=`
|
|
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 Am(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=Em,document.head.appendChild(e)}const fl=Dc(function({entityName:t,entityType:r,entitySha:s,entityFilePath:o,scenarioName:a,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:p,onShowResults:u,onHideResults:m,editorMode:h,onIdleChange:f,notificationsEnabled:y},g){const x=be(null),v=be(null),b=be(null),w=be(null),S=be(null),E=be(!1),k=be(0),N=be(!1),C=be(f);C.current=f;const A=be(y);A.current=y;const T=ae(()=>{var P;(P=b.current)==null||P.focus()},[]);return Oc(g,()=>({sendInput(P){const _=w.current;_&&_.readyState===WebSocket.OPEN&&(_.send(JSON.stringify({type:"input",data:P})),setTimeout(()=>{_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var P;(P=b.current)==null||P.focus()},scrollToBottom(){var _;const P=(_=x.current)==null?void 0:_.querySelector(".xterm-viewport");P&&(P.scrollTop=P.scrollHeight)}})),te(()=>{const P=x.current;if(!P)return;let _=!1;return Am(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([$,I,R])=>{if(_)return;const Y=new $.Terminal({cursorBlink:!0,scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(U,Z){try{const z=new URL(Z),L=z.searchParams.get("scenario");if(L&&z.pathname==="/editor"){const J=new BroadcastChannel("codeyam-editor");J.postMessage({type:"switch-scenario",scenarioId:L}),J.close();return}}catch{}window.open(Z,"_blank")}}}),H=new I.FitAddon;Y.loadAddon(H),Y.loadAddon(new R.WebLinksAddon),Y.open(P);let W=null;km(Y,(U,Z,z)=>{console.warn(`[Terminal] Renderer fallback: ${U} → ${Z}`,z)}).then(U=>{if(_){U.dispose();return}console.log(`[Terminal] Using ${U.type} renderer`),W=U.dispose}),requestAnimationFrame(()=>{try{H.fit()}catch{}}),b.current=Y,Y.focus(),setTimeout(()=>Y.focus(),100),setTimeout(()=>Y.focus(),500);const B=window.location.protocol==="https:"?"wss:":"ws:",D=window.location.host;function O(U){const Z=new URLSearchParams;return Z.set("entityName",t),r&&Z.set("entityType",r),s&&Z.set("entitySha",s),o&&Z.set("entityFilePath",o),a&&Z.set("scenarioName",a),i&&Z.set("scenarioDescription",i),l&&Z.set("analysisId",l),c&&Z.set("projectSlug",c),h&&Z.set("editorMode","true"),U&&Z.set("reconnectId",U),`${B}//${D}/ws/terminal?${Z.toString()}`}function j(U){const Z=O(U),z=new WebSocket(Z);w.current=z,z.onopen=()=>{k.current=0,N.current=!1,z.send(JSON.stringify({type:"resize",cols:Y.cols,rows:Y.rows}))},z.onmessage=L=>{var J,G;try{const X=JSON.parse(L.data);if(X.type==="session-id"){S.current=X.sessionId;return}if(X.type==="refresh-preview"){p==null||p(X.path,X.scenarioId);return}if(X.type==="show-results"){u==null||u();return}if(X.type==="hide-results"){m==null||m();return}if(X.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",A.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(J=C.current)==null||J.call(C,!0),A.current&&typeof Notification<"u"&&Notification.permission==="granted"){const le=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});le.onclick=()=>{window.focus(),le.close()}}return}X.type==="output"&&(Y.write(X.data),(G=C.current)==null||G.call(C,!1))}catch{Y.write(L.data)}},z.onclose=()=>{if(E.current){Y.write(`\r
|
|
110
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
111
|
+
`);return}const L=k.current;if(L<5&&S.current){const J=1e3*Math.pow(2,Math.min(L,3));k.current=L+1,Y.write(`\r
|
|
112
|
+
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
113
|
+
`),setTimeout(()=>{E.current||j(S.current)},J)}else N.current?Y.write(`\r
|
|
114
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
115
|
+
`):(N.current=!0,Y.write(`\r
|
|
116
|
+
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
117
|
+
`),S.current=null,k.current=0,j())},z.onerror=()=>{}}j(),Y.onData(U=>{const Z=w.current;Z&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"input",data:U}))});let q=null;const V=new ResizeObserver(()=>{q&&clearTimeout(q),q=setTimeout(()=>{let U;try{U=H.proposeDimensions()}catch{return}if(!U||U.cols===Y.cols&&U.rows===Y.rows)return;const Z=P.querySelector(".xterm-viewport");let z,L=!0;Z&&(z=Z.scrollTop,L=Z.scrollTop+Z.clientHeight>=Z.scrollHeight-10),H.fit(),Z&&z!==void 0&&(L?Z.scrollTop=Z.scrollHeight:Z.scrollTop=z);const J=w.current;J&&J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"resize",cols:Y.cols,rows:Y.rows}))},150)});V.observe(P),v.current=()=>{var U;q&&clearTimeout(q),V.disconnect(),E.current=!0,(U=w.current)==null||U.close(),w.current=null,W==null||W(),Y.dispose(),b.current=null}}),()=>{var $;_=!0,($=v.current)==null||$.call(v),v.current=null}},[]),n("div",{ref:x,onClick:T,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function Ge({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:o}){const[a,i]=M("loading"),[l,c]=M(!1),p=be(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),c(!0)},h=()=>{i("error"),c(!1)};return te(()=>{i("loading"),c(!1);const f=p.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[u]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:o,children:[n("img",{ref:p,src:u,alt:r,onLoad:m,onError:h,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),a==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),a==="error"&&d("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:o,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Pm({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const o=Et();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(a=>{var c,p;const i=a.id===t,l=(p=(c=a.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0];return d("button",{onClick:()=>{o(`/entity/${r}/scenarios/${a.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(Ge,{screenshotPath:l,cacheBuster:s,alt:a.name,className:"w-full h-full object-cover object-top"})}),d("div",{className:"p-2.5 min-w-0 flex-1",children:[d("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),a.name]}),a.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:a.description})]})]},a.id)})})}function kt(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Ct(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function No(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function Ys(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function _m(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:o,proxyUrl:a,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const p=o.find(u=>u.id===s);if(p!=null&&p.url){const u=a||i;return u?p.url.startsWith("/")?`${u}${p.url}`:p.url:null}}const c=a||i;if(!c)return null;if(l&&s){const p=o.find(m=>m.id===s),u=p?Ct(p.name):"Default";return`${c}/__codeyam__/${l}/${u}`}return c}function gl(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function jm(e,t){return e?e!==t:!1}function Mm(e,t){const r=t.width,s=t.height??900,o=e.width,a=e.height;return r<=o&&s<=a?1:Math.min(o/r,a/s)}async function Tm({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await an(t);if(!s)throw Q("Entity not found",{status:404});const o=await Jr(s),a=((l=o==null?void 0:o.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!a)throw Q("Scenario not found",{status:404});const i=await Te();return Q({entity:s,scenario:a,analysis:o,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}],$m=We(function(){const{entity:t,scenario:r,analysis:s,projectSlug:o}=Ve(),a=Et(),i=be(null),l=be(null),[c,p]=M(null),[u,m]=M(1440),[h,f]=M({name:"Desktop",width:1440,height:900}),[y,g]=M(!1),[x,v]=M(null),[b,w]=M("chat"),[S,E]=M(0),[k,N]=M(null),C=ae(oe=>{N(oe||null),E(me=>me+1)},[]),{customSizes:A,addCustomSize:T}=Xr(o),P=ne(()=>[...Ns,...A],[A]),{interactiveServerUrl:_,isStarting:$,isLoading:I,showIframe:R,iframeKey:Y,onIframeLoad:H}=dn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0,refreshTrigger:S}),W=ne(()=>gl(_,k),[_,k]),{lastLine:B}=Pt(o,$||I),D=()=>{a(`/entity/${t.sha}`)},O=(oe,me)=>{m(oe);const Ce=P.find(je=>je.width===oe&&je.height===me);p(Ce||null),f({name:(Ce==null?void 0:Ce.name)||"Custom",width:oe,height:me})},j=oe=>{p(oe),m(oe.width),f({name:oe.name,width:oe.width,height:oe.height})},q=oe=>{T(oe,h.width,h.height??900),g(!1),f(me=>({...me,name:oe}))},V=()=>{var me;w("chat"),(me=l.current)==null||me.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.")},U=((s==null?void 0:s.scenarios)||[]).filter(oe=>{var me;return!((me=oe.metadata)!=null&&me.sameAsDefault)}),Z=U.findIndex(oe=>oe.id===(r==null?void 0:r.id)),z=Z+1,L=U.length,J=Z>0,G=Z<U.length-1,X=()=>{if(J){const oe=U[Z-1];a(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},le=()=>{if(G){const oe=U[Z+1];a(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},xe=$||I||!R;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Br,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:X,disabled:!J,className:`${J?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[z,"/",L]}),n("button",{onClick:le,disabled:!G,className:`${G?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:D,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Ns[Ns.length-1].width}px`,width:"100%"},children:n(wo,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:j,devicePresets:P,hideLabel:!0,onHoverChange:v,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:h.name,onChange:oe=>{const me=P.find(Ce=>Ce.name===oe.target.value);me&&j(me)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[P.map(oe=>n("option",{value:oe.name,children:oe.name},oe.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:oe=>{const me=parseInt(oe.target.value,10);!isNaN(me)&&me>0&&O(me,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"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:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
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:_?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[xe&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),B&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),B]})]})]})}),n("iframe",{ref:i,src:W||_,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:H,style:{opacity:R?1:0}},Y)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),B&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),B]})]})]})})]}),d("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[d("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-0",children:[d("button",{onClick:()=>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]"})]}),d("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:V,disabled:!_,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(fl,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:o,onRefreshPreview:C})}),b==="scenarios"&&n(Pm,{scenarios:U,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(hl,{serverUrl:_,isStarting:$,projectSlug:o}),y&&n(Zr,{width:h.width,height:h.height??900,onSave:q,onCancel:()=>g(!1)})]})}),Rm=Object.freeze(Object.defineProperty({__proto__:null,default:$m,loader:Tm},Symbol.toStringTag,{value:"Module"}));async function Im({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:o,viewportHeight:a}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=F.join(i,".codeyam","journal","screenshots");await ve.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),p=F.join(l,`${c}.png`),u=F.dirname(new URL(import.meta.url).pathname);let m=u;for(let v=0;v<5;v++){const b=F.dirname(m);if(F.basename(b)==="webserver"||F.basename(m)==="webserver"){m=F.basename(m)==="webserver"?m:b;break}m=b}const h=[F.join(m,"scripts","journalCapture.ts"),F.join(m,"app","lib","journalCapture.ts"),F.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),F.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of h)try{await ve.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${h.join(", ")}`),f=h[0]);const y=JSON.stringify({url:r,outputPath:p,viewportWidth:o,viewportHeight:a}),g=await new Promise(v=>{const b=At("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let w="",S="";b.stdout.on("data",E=>{w+=E.toString()}),b.stderr.on("data",E=>{S+=E.toString()}),b.on("close",E=>{v(E===0?{success:!0,output:w}:{success:!1,output:w,error:S||`Process exited with code ${E}`})}),b.on("error",E=>{v({success:!1,output:"",error:E.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/${c}.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 Dm=Object.freeze(Object.defineProperty({__proto__:null,action:Im},Symbol.toStringTag,{value:"Module"})),yl=ro({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Co=()=>{const e=Or(yl);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},es=({children:e})=>{const[t,r]=M({height:720,width:1200}),[s,o]=M(1),[a,i]=M(1200),l=be(null),c=ae(({height:m,width:h})=>{r(f=>({height:m??f.height,width:h??f.width}))},[]),p=ae(m=>{o(m)},[]),u=ae(m=>{i(m)},[]);return n(yl.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:p,maxWidth:a,updateMaxWidth:u},children:e})},Om=typeof window<"u";function Lm(){const[e,t]=M(null);return te(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Fm=1200,zm=720,Ma=30,Bm=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:o=900,onDataOverride:a,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const p=Lm(),[u,m]=M(!1),[h,f]=M(!1),[y,g]=M(Fm),[x,v]=M(zm),[b,w]=M(null),[S,E]=M(null),{dimensions:k,updateDimensions:N,iframeRef:C,updateScale:A,updateMaxWidth:T}=Co(),P=ne(()=>Math.min(1,y/k.width),[y,k.width]),_=S!==null?S:P;te(()=>{u||(A(_),l==null||l(_))},[_,A,l,u]),te(()=>{T(y)},[y,T]);const $=ae(()=>{m(!0),E(P)},[P]),I=ae(()=>{m(!1),E(null)},[]),R=ae((D,O)=>{const j=S!==null?S:1,q=Math.round(O.size.width/j);N({width:q}),c==null||c(q,k.height)},[N,S,c,k.height]),Y=ae(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);te(()=>{const D=O=>{if(O.data.type==="codeyam-resize"){if(t&&O.data.name!==t||k.height===O.data.height||O.data.height===0)return;N({height:O.data.height})}};return window.addEventListener("message",D),()=>{window.removeEventListener("message",D)}},[C,t,s,k,N]),te(()=>{h&&a&&a(C.current)},[h,a,C]),te(()=>{if(!t)return;const D=setInterval(()=>{var O,j;(j=(O=C==null?void 0:C.current)==null?void 0:O.contentWindow)==null||j.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(D)},[t,C]),te(()=>{const D=()=>{const O=document.getElementById("scenario-container");if(!O)return;const j=O.getBoundingClientRect(),q=O.clientWidth-Ma*2,V=window.innerHeight-j.top-Ma*2,U=Math.max(V,400),Z=window.innerHeight-j.top;g(q),v(U),w(Z)};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]),te(()=>{N({width:s,height:o})},[s,o,N]);const H=ne(()=>k.width*_,[k.width,_]),W=ne(()=>{const D=k.height,O=D*_;return D&&D!==720&&D!==900&&O<x?O:x},[k.height,x,_]),B=ae(()=>{window.history.back()},[]);return!Om||!p?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style: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(p,{width:H,height:W,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:$,onResizeStop:I,onResize:R,children:n("div",{className:"overflow-auto",style:{width:`${H}px`,height:`${W}px`},children:n("div",{style:{width:`${k.width}px`,height:`${k.height}px`,transform:`scale(${_})`,transformOrigin:"top left"},children:r?n("iframe",{ref:C,className:"w-full h-full rounded-lg",src:r,onLoad:Y,sandbox:"allow-scripts allow-same-origin"}):d("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:B,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Ym({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:o,onSizeChange:a,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[p,u]=M(!1),[m,h]=M(String(r)),[f,y]=M(String(s)),[g,x]=M(!1),[v,b]=M(!1),w=be(null);te(()=>{g||h(String(r))},[r,g]),te(()=>{v||y(String(s))},[s,v]),te(()=>{const _=$=>{w.current&&!w.current.contains($.target)&&u(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const S=ne(()=>{const _=e.find(I=>I.width===r&&I.height===s);if(_)return _.name;const $=t.find(I=>I.width===r&&I.height===s);return $?$.name:"Custom"},[e,t,r,s]),E=S==="Custom",k=_=>{a(_.width,_.height),u(!1)},N=_=>{const $=_.target.value;h($);const I=parseInt($,10);!isNaN(I)&&I>0&&a(I,s)},C=_=>{const $=_.target.value;y($);const I=parseInt($,10);!isNaN(I)&&I>0&&a(r,I)},A=()=>{x(!1);const _=parseInt(m,10);(isNaN(_)||_<=0)&&h(String(r))},T=()=>{b(!1);const _=parseInt(f,10);(isNaN(_)||_<=0)&&y(String(s))},P=_=>{(_.key==="Enter"||_.key==="Escape")&&_.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:w,children:[d("button",{onClick:()=>u(!p),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:S}),n("svg",{className:`w-4 h-4 transition-transform ${p?"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"})})]}),p&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:d("div",{className:"py-1",children:[e.length>0&&d(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(_=>d("button",{onClick:()=>k(_),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${S===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:_.name}),d("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]},_.name))]}),t.length>0&&d(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((_,$)=>_.width-$.width).map(_=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${S===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>k(_),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:_.name}),d("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]}),l&&n("button",{onClick:$=>{$.stopPropagation(),S===_.name&&e.length>0&&a(e[0].width,e[0].height),l(_.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"})})})]},_.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:N,onFocus:()=>x(!0),onBlur:A,onKeyDown:P,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),d("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:C,onFocus:()=>b(!0),onBlur:T,onKeyDown:P,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),o!==void 0&&o<1&&d("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),E&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function Cs(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 Us(e){return e&&(typeof e=="object"||Array.isArray(e))}function Um(e){return Array.isArray(e)?e.length:void 0}function Wm(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,o)=>o.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((o,a)=>{const i=Us(t[o]),l=Us(t[a]);return i&&!l?1:!i&&l?-1:o.localeCompare(a)});if(typeof t=="object")return Object.keys(t).sort((o,a)=>o.localeCompare(a))}}function Jm({scenarioFormData:e,handleInputChange:t}){return d("div",{className:"p-3 flex flex-col gap-3",children:[d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),d("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Hm({path:e,namedPath:t,isArray:r,count:s,onClick:o}){const a=ae(()=>{o&&o(e)},[o,e]);return d("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:a,children:[d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),d("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var xl=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(xl||{});const Vm=({name:e,value:t,options:r,onChange:s})=>{const o=ae(a=>{s({target:{name:e,value:a.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:o,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((a,i)=>n("option",{value:a.trim(),children:a.trim()},i))})},Gm=({name:e,value:t,onChange:r})=>{const s=ae(o=>{const a=o.target.checked;r({target:{name:e,value:a}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
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 qm({dataType:e,path:t,value:r,onChange:s}){const o=ne(()=>t[t.length-1],[t]),a=ne(()=>t.join("-"),[t]),i=ae(c=>{s(t,c.target.value)},[s,t]),l=ae(c=>{s(t,c.target.value)},[s,t]);return d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:a,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?n(Vm,{name:a,value:r,options:e.split("|"),onChange:i}):e===xl.BOOLEAN?n(Gm,{name:a,value:r??!1,onChange:l}):n("input",{id:a,name:a,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${a}`)]})}function Km({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:o}){const[a,i]=M(!1),[l,c]=M(""),p=ae(async()=>{if(!o){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 h=e.scenarios.find(x=>x.name===Yr),f=await o(l,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((h==null?void 0:h.metadata.data)||{},m.metadata.data),f.data||{}),s(m),i(!1),c("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,l,r,t,s,o]),u=ae(m=>{c(m.target.value)},[]);return d("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:a,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void p(),children:a?d(ue,{children:[d("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Qm({namedPath:e,path:t,last:r,onClick:s}){const o=ae(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function Zm({dataItem:e,onClick:t}){const r=ae(()=>t([]),[t]),s=ne(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return d("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&d("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((o,a)=>d("div",{className:"flex items-center gap-1",children:[n(Qm,{namedPath:e.namedPath.slice(0,a+s+1),path:e.path.slice(0,a+s+1),last:a+s===e.namedPath.length-1,onClick:t}),a+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${o}-${a+s}`))]})}function Ta({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:o,onAIResult:a,onGenerateData:i,saveFeedback:l}){const c=ne(()=>r.data,[r]),p=ne(()=>Wm(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Zm,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(Km,{analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:i}),p==null?void 0:p.map((u,m)=>{var f;if(Us(c[u])){let y=u;isNaN(Number(u))||(y=c[u].name??c[u].title??c[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(Hm,{path:g,namedPath:x,isArray:Array.isArray(c),count:Um(c[u]),onClick:s},`data-${u}-${m}`)}if(u==="id")return null;const h=[...r.path,u];return n(qm,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:h,value:c[u],onChange:o},`InputField-${h.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function $a({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:o=!1}){const[a,i]=M(r),l=[];return s&&l.push("border-t"),o&&l.push("border-b"),d("div",{className:`${l.join(" ")} border-gray-300`,children:[d("button",{type:"button",onClick:()=>i(!a),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${a?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),a&&n("div",{className:"px-4 py-3",children:t})]})}const Xm=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:o,onSave:a,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:p})=>{const u=ae((N,C)=>{const A=Object.assign({},N),T=P=>P&&typeof P=="object"&&!Array.isArray(P);return T(N)&&T(C)&&Object.keys(C).forEach(P=>{T(C[P])?P in N?A[P]=u(N[P],C[P]):Object.assign(A,{[P]:C[P]}):Object.assign(A,{[P]:C[P]})}),A},[]),[m,h]=M({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=M(null),g=ne(()=>({...m.data}),[m]),x=ne(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=ne(()=>{const N={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(N).reduce((C,A)=>{if(A.includes(".")){const[T,P]=A.split(".");C[T]||(C[T]={}),C[T][P]=N[A]}else C[A]=N[A];return C},{})},[r]),b=ae(async N=>{N.preventDefault();const C=N.target.querySelector('input[name="recapture"]'),A=(C==null?void 0:C.value)==="true",T={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:A,dataToSave:T,rawFormData:m.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(T,null,2).substring(0,1e3));const P=s==null?void 0:s.scenarios.map(_=>!o&&_.name===e.name?{..._,name:m.name,description:m.description,metadata:{..._.metadata,data:T}}:_);o&&P.push({name:m.name,description:m.description,metadata:{data:T,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",P),a&&await a(P,{recapture:A}),i&&i(m.name)},[s,e.name,m,g,o,a,i]),w=ae(N=>{h(C=>({...C,[N.target.name]:N.target.value}))},[]),S=ae(N=>{y(C=>{if(!C)return null;for(const A of[{arguments:N.metadata.data.argumentsData},N.metadata.data.mockData]){let T=A;for(const P of C.path)if(T=Cs(T,P),!T)break;T&&(C.data=T)}return{...C}}),h({name:N.name,description:N.description,data:N.metadata.data})},[]),E=ae((N,C)=>{h(A=>{for(const T of[{"Function Arguments":A.data.argumentsData},{"Retrieved Data":A.data.mockData}]){let P=T;for(const _ of N.slice(0,-1))if(P=Cs(P,_),!P)break;if(P){const _=P[N[N.length-1]];y($=>$?($.namedPath[$.namedPath.length-1]===_&&($.namedPath[$.namedPath.length-1]=C.toString()),$.data[N[N.length-1]]=C,{...$}):null),P[N[N.length-1]]=C}}return{...A}})},[]),k=ae(N=>{var P,_,$;if(N.length===0){y(null);return}let C=x;const A=[];let T=v;for(const I of N){if(A.push(isNaN(parseInt(I))?I:((P=C[I])==null?void 0:P.name)??((_=C[I])==null?void 0:_.title)??(($=C[I])==null?void 0:$.id)??I),C=Cs(C,I),!C){console.log("Data not found",C,I),y(null);return}Array.isArray(T)?T=T[0]:T=T[I]}y({path:N,namedPath:A,data:C,structure:T})},[x,v]);return te(()=>{const N=C=>{var A;C.data.type==="codeyam-log"&&((A=C.data.data)!=null&&A.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",C.data.data)};return window.addEventListener("message",N),()=>window.removeEventListener("message",N)},[]),te(()=>{var N;if((N=l==null?void 0:l.current)!=null&&N.contentWindow){const C={arguments:g.argumentsData??[],...g.mockData??{}},A={type:"codeyam-override-data",name:e.name,data:JSON.stringify(C)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:A.type,name:A.name,dataPreview:JSON.stringify(C).substring(0,200)+"...",fullData:C}),l.current.contentWindow.postMessage(A,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:N=>void b(N),children:f?n(Ta,{analysis:s,scenarioName:m.name,dataItem:f,onClick:k,onChange:E,onAIResult:S,onGenerateData:c,saveFeedback:p}):d(ue,{children:[n($a,{title:"Edit Name and Description",borderT:!0,children:n(Jm,{scenarioFormData:m,handleInputChange:w})}),e.metadata.data&&n($a,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Ta,{analysis:s,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:k,onChange:E,onAIResult:S,onGenerateData:c,saveFeedback:p})})]})})};function ts({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:o,showIframe:a,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:p,projectSlug:u,defaultWidth:m=1440,defaultHeight:h=900,retryCount:f=0}){const{lastLine:y}=Pt(u??null,s||o);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:a?1:0,background:"transparent"},children:n(Bm,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:h,onIframeLoad:l,onScaleChange:c,onDimensionChange:p},i)}),!a&&(s||o)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(bn,{}),y]})]})]})})}const eh=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function th({params:e}){var c,p;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 Wr(t,!0),o=s&&s.length>0?s[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const a=(c=o.scenarios)==null?void 0:c.find(u=>u.id===r);if(!a)throw new Response("Scenario not found",{status:404});const i=(p=o.scenarios)==null?void 0:p.find(u=>u.name===Yr),l=await Te();return Q({analysis:o,scenario:a,defaultScenario:i||a,entitySha:t,projectSlug:l})}function nh(){var I,R,Y;const e=Ve(),t=e.analysis,r=e.scenario,s=e.defaultScenario,o=e.entitySha,a=e.projectSlug,i=Et(),{iframeRef:l}=Co(),[c,p]=M(!1),[u,m]=M(null),[h,f]=M(null),[y,g]=M(!1),[x,v]=M(!1),[b,w]=M(null),{interactiveServerUrl:S,isStarting:E,isLoading:k,showIframe:N,iframeKey:C,onIframeLoad:A}=dn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),T=ae(async(H,W)=>{p(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",W),console.log("[EditScenario] Scenarios to save:",H);try{const B={analysis:t,scenarios:H};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:H.length,scenarioNames:H.map(j=>j.name)});const D=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)}),O=await D.json();if(console.log("[EditScenario] API response:",O),!D.ok||!O.success)throw new Error(O.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),W!=null&&W.recapture&&r.id&&S){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:S}),m("Changes saved. Capturing screenshot...");const j={serverUrl:S,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",j);const q=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)});console.log("[EditScenario] Capture response status:",q.status);const V=await q.json();if(console.log("[EditScenario] Capture response body:",V),!q.ok||!V.success)throw console.error("[EditScenario] Capture failed:",V),new Error(V.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",V),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(W!=null&&W.recapture&&!S){console.log("[EditScenario] No running server, using queued recapture");const j=new FormData;j.append("analysisId",t.id||""),j.append("scenarioId",r.id||"");const q=await fetch("/api/recapture-scenario",{method:"POST",body:j}),V=await q.json();if(!q.ok||!V.success)throw new Error(V.error||"Failed to trigger recapture");console.log("Recapture queued:",V),f(V.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(B){console.error("Error saving scenarios:",B),m(`Error: ${B instanceof Error?B.message:String(B)}`)}finally{p(!1)}},[t,r.id,S]),P=ae(H=>{},[]),_=ae(async(H,W)=>{var O;const B=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:H,existingScenarios:t.scenarios,scenariosDataStructure:(O=t.metadata)==null?void 0:O.scenariosDataStructure,editingMockName:r.name,editingMockData:W==null?void 0:W.data})}),D=await B.json();if(!B.ok||!D.success)throw new Error(D.error||"Failed to generate scenario data");return D.data},[t,r.name]),$=ae(async()=>{var H;if(!r.id){w("Cannot delete scenario without ID");return}g(!0),w(null);try{const W=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((H=r.metadata)==null?void 0:H.screenshotPaths)||[]})}),B=await W.json();if(!W.ok||!B.success)throw new Error(B.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(W){console.error("[EditScenario] Error deleting scenario:",W),w(W instanceof Error?W.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,(I=r.metadata)==null?void 0:I.screenshotPaths,o,i]);return d("div",{className:"h-screen bg-gray-50 flex flex-col",children:[d("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:d(de,{to:`/entity/${o}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(R=t.entity)==null?void 0:R.name]})}),d("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[d("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Xm,{currentScenario:r,defaultScenario:s,dataStructure:((Y=t.metadata)==null?void 0:Y.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:T,onNavigate:P,iframeRef:l,onGenerateData:_,saveFeedback:{isSaving:c,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/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),d("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?d("div",{className:"space-y-3",children:[d("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void $(),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(ts,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:S,isStarting:E,isLoading:k,showIframe:N,iframeKey:C,onIframeLoad:A,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const rh=We(function(){return n(es,{children:n(nh,{})})}),sh=Object.freeze(Object.defineProperty({__proto__:null,default:rh,loader:th,meta:eh},Symbol.toStringTag,{value:"Module"}));function oh(e){return qn.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function ah(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function ih(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,o)=>(t.push(o),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function lh(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function ch(){let e=[],t={},r=null,s=null,o=!1,a=null;function i(p){const u=[],m=p.routes;if(m&&typeof m=="object")for(const[h,f]of Object.entries(m)){const{method:y,pathPattern:g}=ah(h),{regex:x,paramNames:v}=ih(g),b=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:v,response:{body:b.body,status:typeof b.status=="number"?b.status:200}})}return u}function l(p){const u=p.state;if(u&&typeof u=="object"){o=!0,t={};for(const[m,h]of Object.entries(u))t[m]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[];r=JSON.stringify(u)}else o=!1,t={},r=null}return{loadScenario(p){const u=oh(p);s&&u===s||(s=u,a=p,e=i(p),l(p))},matchRequest(p,u,m){if(!a&&e.length===0&&!o)return null;const h=Object.keys(t);if(o){const y=lh(u,h);if(y&&p==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=c(p,u);if(p==="POST"&&y===u&&g){const x=t[y],v=typeof m=="object"&&m!==null?{...m}:{};if(!("id"in v)){const b=x.reduce((w,S)=>{const E=typeof S.id=="number"?S.id:0;return Math.max(w,E)},0);v.id=b+1}return x.push(v),{body:v,status:g.response.status}}if(p==="DELETE"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(w=>String(w.id)===String(x));return b===-1?{body:{error:"Not found"},status:404}:(v.splice(b,1),{body:null,status:g.response.status})}if(p==="PUT"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(S=>String(S.id)===String(x));if(b===-1)return{body:{error:"Not found"},status:404};const w=typeof m=="object"&&m!==null?{...m}:v[b];return v[b]=w,{body:w,status:g.response.status}}}}const f=c(p,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(a&&p==="GET"){const y=u.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in a&&g!=="routes"&&g!=="state")return{body:a[g],status:200}}}return null},resetState(){if(r){const p=JSON.parse(r);t={};for(const[u,m]of Object.entries(p))t[u]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[]}},getState(){return{...t}}};function c(p,u){for(const m of e)if(m.method!==null&&m.method===p&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response};if(p==="GET"){for(const m of e)if(m.method===null&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response}}for(const m of e)if(m.paramNames.length>0){if((m.method??"GET")!==p)continue;const f=m.pathRegex.exec(u);if(f){const y={};for(let g=0;g<m.paramNames.length;g++)y[m.paramNames[g]]=f[g+1];return{response:m.response,params:y}}}return null}}function dh(e){var o,a;const t=ee.join(e,"package.json");if(!fe.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(fe.readFileSync(t,"utf8"));if(fe.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":fe.existsSync(ee.join(e,"yarn.lock"))?r="yarn":fe.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((o=i.scripts)!=null&&o.dev))if((a=i.scripts)!=null&&a.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function uh(e,t){const r=t.toString(),s={PORT:r},o=ee.join(e,".codeyam","config.json");if(fe.existsSync(o))try{const c=(JSON.parse(fe.readFileSync(o,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:p,args:u,env:m}=c.startCommand,h=(u||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(m)for(const[f,y]of Object.entries(m))typeof y=="string"&&y.includes("$PORT")?s[f]=y.replace(/\$PORT/g,r):typeof y=="string"&&(s[f]=y);return{command:p,args:h,env:s}}}catch{}const a=dh(e);return"error"in a?a:{command:a.command,args:a.args,env:s}}function bl(e){return{proxyPort:e+1,devServerPort:e+2}}const ph=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/waiting on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function mh(e){for(const t of ph){const r=e.match(t);if(r){const s=r[1]||r[0];return hh(s).trim()}}return null}function hh(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function vl(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function fh(e,t={}){const{intervalMs:r=2e3,maxAttempts:s=15}=t,o=`http://localhost:${e}`;for(let a=0;a<s;a++){try{const i=await fetch(o,{method:"HEAD",signal:AbortSignal.timeout(2e3)});if(i.ok||i.status===304)return o}catch{}a<s-1&&await new Promise(i=>setTimeout(i,r))}return null}function gh(e){const{exitCode:t,uptime:r,retryCount:s}=e,o=r<1e4;return t!==0&&t!==null&&o&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:{action:"stopped"}}function yh(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function xh(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(o=>{const a=new $i.Socket;a.setTimeout(1e3),a.once("connect",()=>{a.destroy(),o(!0)}),a.once("error",()=>{a.destroy(),o(!1)}),a.once("timeout",()=>{a.destroy(),o(!1)}),a.connect(e,r)}))return r}catch{}return null}const wl="__codeyam_editor_proxy__",bh=500;let Nt={data:null,timestamp:0},en;const Ra=10*1024*1024;function So(){return globalThis[wl]??null}function Nl(e){globalThis[wl]=e}function Cl(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=ch()),globalThis[e]}function Sl(){const e=So();return e?`http://localhost:${e.port}`:null}function vh(){const e=Date.now();if(Nt.data!==null&&e-Nt.timestamp<bh)return Nt.data;const t=pe()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!fe.existsSync(r))return Nt={data:null,timestamp:e},null;const s=JSON.parse(fe.readFileSync(r,"utf-8")),o=s.scenarioId;if(!o)return Nt={data:null,timestamp:e},null;const a=ee.join(t,".codeyam","editor-scenarios",`${o}.json`);if(!fe.existsSync(a))return console.log(`[editorProxy] Scenario data file not found: ${a}`),Nt={data:null,timestamp:e},null;const i=JSON.parse(fe.readFileSync(a,"utf-8"));en=i.session||null;const l=s.type||i.type||null;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Nt={data:c,timestamp:e},Cl().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Nt={data:null,timestamp:e},null}}function wh(e){return new Promise(t=>{const r=[];let s=0;e.on("data",o=>{s+=o.length,s>Ra?(t(null),e.resume()):r.push(o)}),e.on("end",()=>{s>Ra||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function ko(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Ia(e,t,r,s){const o=new URL(r),a=ko(o.hostname),i={...e.headers,host:`${o.hostname}:${o.port}`};s&&(i["content-length"]=String(s.length));const l={hostname:a,port:o.port,path:e.url,method:e.method,headers:i},c=uo.request(l,p=>{const u=p.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const m={...p.headers};kl(m),t.writeHead(u,m),p.pipe(t,{end:!0})});c.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function Nh(e,t,r){const s=new URL(r),a={hostname:ko(s.hostname),port:s.port,path:e.url,method:e.method,headers:{...e.headers,host:`${s.hostname}:${s.port}`}},i=uo.request(a,l=>{const c=l.statusCode||200;c>=400&&console.warn(`[editorProxy] Target returned ${c} for ${e.method} ${e.url}`);const p={...l.headers};kl(p),t.writeHead(c,p),l.pipe(t,{end:!0})});i.on("error",l=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${l.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(i,{end:!0})}function kl(e){if(en===void 0)return;let t;en!=null&&en.cookieValue?t=`session-token=${en.cookieValue}; Path=/; SameSite=Lax`:t="session-token=; Path=/; Max-Age=0";const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],t]:e["set-cookie"]=[t]}function Ch(e,t,r,s){const o=new URL(s),a=ko(o.hostname),i=parseInt(o.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a}:${i}`);const l=$i.connect(i,a,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
150
|
+
`,p=Object.entries(e.headers).filter(([,u])=>u!=null).map(([u,m])=>`${u}: ${Array.isArray(m)?m.join(", "):m}`).join(`\r
|
|
151
|
+
`);l.write(c+p+`\r
|
|
152
|
+
\r
|
|
153
|
+
`),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function Sh(e,t){const r=pe()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{fe.mkdirSync(ee.dirname(s),{recursive:!0}),fe.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(o){console.warn("[editorProxy] Failed to write proxy-config.json:",o)}}function kh(){const e=pe()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{fe.existsSync(t)&&fe.unlinkSync(t)}catch{}}async function Ws(e){await El();let t=yh(e.targetUrl),r=e.port;try{const i=new URL(t);if(i.hostname==="localhost"){const l=parseInt(i.port||"80",10),c=await xh(l);c&&(i.hostname=c,t=i.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${c} for port ${l}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${r}, target ${t})`);const s=Cl(),o=uo.createServer((i,l)=>{(async()=>{const p=new URL(i.url||"/",`http://localhost:${r}`).pathname,u=i.method||"GET";if(u==="OPTIONS"){l.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),l.end();return}if(vh(),u==="POST"||u==="PUT"||u==="DELETE"||u==="PATCH"){const f=await wh(i);if(f===null){Ia(i,l,t,null);return}let y;if(f.length>0)try{y=JSON.parse(f.toString("utf-8"))}catch{}const g=s.matchRequest(u,p,y);if(g){console.log(`[editorProxy] Intercepted ${u} ${p} → mock response (status ${g.status})`),l.writeHead(g.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),l.end(g.body!=null?JSON.stringify(g.body):"");return}Ia(i,l,t,f);return}const h=s.matchRequest(u,p);if(h){console.log(`[editorProxy] Intercepted ${u} ${p} → mock response (status ${h.status})`),l.writeHead(h.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),l.end(h.body!=null?JSON.stringify(h.body):"");return}Nh(i,l,t)})()});o.on("upgrade",(i,l,c)=>{Ch(i,l,c,t)});const a=10;for(let i=0;i<a;i++){const l=r+i;try{await new Promise((u,m)=>{o.once("error",m),o.listen(l,"0.0.0.0",()=>{o.removeListener("error",m),u()})});const c=o.address();return r=typeof c=="object"&&c!==null?c.port:l,Nl({server:o,port:r,targetUrl:t}),Sh(r,t),console.log(`[editorProxy] Proxy started on port ${r}, forwarding to ${t}`),{port:r}}catch(c){if((c==null?void 0:c.code)==="EADDRINUSE"&&i<a-1){console.log(`[editorProxy] Port ${l} in use, trying ${l+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",c),null}}return null}async function El(){const e=So();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),kh(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Nl(null),setTimeout(t,2e3)})}function Bn(){Nt={data:null,timestamp:0},en=void 0}async function Da(){const e=So();if(!e)return console.warn("[editorProxy] Cannot verify — proxy is not running"),!1;try{const t=await fetch(`http://127.0.0.1:${e.port}/`,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return t.status===502?(console.warn("[editorProxy] Verification failed — proxy returned 502 (target unreachable)"),!1):(console.log(`[editorProxy] Verification passed — proxy forwarding to ${e.targetUrl} (status ${t.status})`),!0)}catch{return console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${e.port}`),!1}}async function Al(){const e=Sl();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:s}=bl(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const o=await Ws({port:s,targetUrl:t.url});if(o){const a=`http://localhost:${o.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}function Pl(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 _l(e,t,r,s){const o=F.join(e,".codeyam","editor-scenarios","client-errors.json");let a={};try{const i=await ve.readFile(o,"utf8");a=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(a))i!==t&&l.scenarioName===r&&delete a[i];a[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await ve.mkdir(F.dirname(o),{recursive:!0}),await ve.writeFile(o,JSON.stringify(a,null,2),"utf8")}async function jl(e){const t=F.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await ve.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function Js(e){let r=F.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const o=F.dirname(r);if(F.basename(o)==="webserver"||F.basename(r)==="webserver")return F.basename(r)==="webserver"?r:o;r=o}return r}async function Hs(e,t){const r=[F.join(e,"scripts","journalCapture.ts"),F.join(e,"app","lib","journalCapture.ts"),F.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await ve.access(s),s}catch{}return r[0]}function Vs(e,t,r){return new Promise(s=>{const o=e.endsWith(".ts"),l=At(o?"npx":e,o?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",p="";l.stdout.on("data",u=>{c+=u.toString()}),l.stderr.on("data",u=>{p+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:c}:{success:!1,output:c,error:p||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}const Eh=3e4;function Eo(e,t,r){const s=Eh,o=F.basename(F.dirname(e))===".codeyam"?F.dirname(F.dirname(e)):F.dirname(e);return new Promise(a=>{const i=Date.now(),l=e.endsWith(".ts"),u=At(l?"npx":e,l?["tsx",e,t]:[t],{cwd:o,env:{...process.env}});let m="",h="",f=!1;const y=setTimeout(()=>{f=!0,u.kill("SIGTERM")},s);u.stdout.on("data",g=>{m+=g.toString()}),u.stderr.on("data",g=>{h+=g.toString()}),u.on("close",g=>{clearTimeout(y);const x=Date.now()-i;a(f?{success:!1,output:m,error:`Seed adapter timeout after ${s}ms`,durationMs:x}:g===0?{success:!0,output:m,durationMs:x}:{success:!1,output:m,error:h||`Seed adapter exited with code ${g}`,durationMs:x})}),u.on("error",g=>{clearTimeout(y),a({success:!1,output:"",error:g.message,durationMs:Date.now()-i})})})}function Ao(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=F.join(e,".codeyam",r);try{return K.accessSync(s),s}catch{}}return null}function Ah(e,t){const r={};for(const[s,o]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(o));for(const[s,o]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(o));return r}function Ml(e){return F.join(e,".codeyam","scenarios-manifest.json")}function Tl(e){const t=Ml(e);try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function $l(e,t){const r=Ml(e),s=F.dirname(r);K.mkdirSync(s,{recursive:!0}),K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}function Ph(e,t){const r=Tl(e)||{version:1,updatedAt:"",scenarios:[]},s=r.scenarios.findIndex(o=>o.id===t.id);s>=0?r.scenarios[s]=t:r.scenarios.push(t),r.updatedAt=new Date().toISOString(),$l(e,r)}function _h(e,t){const r=Tl(e);r&&(r.scenarios=r.scenarios.filter(s=>s.id!==t),r.updatedAt=new Date().toISOString(),$l(e,r))}const Rl=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Po(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const o of Rl)try{o.ws.readyState===Ri.OPEN&&(o.ws.send(r),s++)}catch{}return s}function jh(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Rl)try{r.ws.readyState===Ri.OPEN&&(r.ws.send(e),t++)}catch{}return t}const Mh=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:jh,broadcastPreviewRefresh:Po},Symbol.toStringTag,{value:"Module"}));let qt=null;async function Th(e){const{scenarioId:t,projectRoot:r}=e,s=ee.join(r,".codeyam"),o=ee.join(s,"editor-scenarios");let a=e.scenarioSlug||null;if(!a)try{const u=ee.join(o,`${t}.json`);fe.existsSync(u)?a=JSON.parse(fe.readFileSync(u,"utf-8")).name||t:a=t}catch{a=t}let i=e.scenarioType||null;if(!i)try{const u=ee.join(o,`${t}.json`);fe.existsSync(u)&&(i=JSON.parse(fe.readFileSync(u,"utf-8")).type||null)}catch{}const l=ee.join(s,"active-scenario.json");fe.mkdirSync(s,{recursive:!0}),fe.writeFileSync(l,JSON.stringify({scenarioSlug:a,scenarioName:e.scenarioName||a,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let c=null;const p=i==="application"||i==="user";if(p)if(qt&&qt.scenarioId===t)c=await qt.promise;else{const u=Ao(r),m=ee.join(o,`${t}.seed.json`);if(u&&fe.existsSync(m)){const h=Eo(u,m).then(f=>({success:f.success,error:f.error}));qt={scenarioId:t,promise:h};try{c=await h}finally{qt&&qt.scenarioId===t&&(qt=null)}}else u||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:a,scenarioId:t,type:i,seeded:p,...c?{seedResult:c}:{}}}function $h(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ae("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Rh(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Rh(e){const t=e.trim().split(`
|
|
155
|
+
`).filter(s=>s.length>0),r=[];for(const s of t){const o=s[0],a=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,c=!1,p;if(o==="A"||a==="A")l="added",c=o==="A";else if(o==="M"||a==="M")l="modified",c=o==="M";else if(o==="D"||a==="D")l="deleted",c=o==="D";else if(o==="R"||a==="R"){l="renamed",c=o==="R";const u=i.indexOf(" -> ");u!==-1&&(p=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else a==="?"?(l="untracked",c=!1):(l="modified",c=o!==" "&&o!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=ee.join(u,i);try{const h=(y,g)=>{const x=fe.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const w=ee.join(y,b.name),S=ee.relative(u,w);b.isDirectory()?v.push(...h(w,g)):b.isFile()&&v.push(S)}return v},f=h(m,u);for(const y of f)r.push({path:y,status:l,staged:c,...p&&{oldPath:p}})}catch(h){console.error(`Failed to expand directory ${i}:`,h)}}else r.push({path:i,status:l,staged:c,...p&&{oldPath:p}})}return r}function Ih(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function Dh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Ae('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return Ae("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ae("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function Oh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
156
|
+
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function kn(){const e=pe();return e?$h(e):[]}function Lh(){const e=pe();return e?Ih(e):null}function Fh(){const e=pe();return e?Dh(e):"main"}function zh(){const e=pe();return e?Oh(e):[]}function Il(e,t){const r=pe();return r?Bh(e,t,r):[]}function Bh(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ae(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
157
|
+
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let p=l[1],u,m;return c==="A"?m="added":c==="M"?m="modified":c==="D"?m="deleted":c.startsWith("R")?(m="renamed",u=l[1],p=l[2]):m="modified",{path:p,status:m,...u&&{oldPath:u}}})}catch(o){return console.error("Failed to get branch diff:",o),[]}}function Dl(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Ae(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let o="";try{o=fe.readFileSync(ee.join(r,e),"utf8")}catch(a){console.error(`Failed to read current file ${e}:`,a),o=""}return{oldContent:s,newContent:o,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Yh(e){const t=pe();return t?Dl(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Uh(e,t,r,s){const o=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Ae(`git show ${t}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let i="";try{i=Ae(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:a,newContent:i,fileName:e}}catch(a){return console.error(`Failed to get branch diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function gr(e,t,r){const s=pe();return s?Uh(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Ol(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function nt(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function _o(e){return e?e.includes("/isolated-components"):!1}function jo(e){return e.componentName?e.componentName:nt(e.url)}function Ll(e,t,r){var a;const s=[],o=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.url!==void 0){const p=nt(i.url);t[p]&&(l=p,c=t[p])}if(l&&c&&!o.has(l)){o.add(l);const p=r.find(u=>u.name===l);s.push({name:l,filePath:c,importedBy:(a=p==null?void 0:p.metadata)==null?void 0:a.importedBy})}}return s}function Wh(e,t){const r=[],s=new Set(t);for(const o of e)s.has(o.name)||(s.add(o.name),r.push({name:o.name,filePath:o.filePath}));return r}function Jh(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function Hh(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const o=jo(r);return!!t[o]}const s=r.name.indexOf(" - ");if(s!==-1){const o=r.name.slice(0,s);return!!t[o]}return!!t.Home})}function Vh(e){const t=new Map;for(const r of e){const s=r.importedBy;if(!s||typeof s!="object")continue;const o=new Set;for(const a of Object.keys(s))for(const i of Object.keys(s[a]))o.add(i);o.size>0&&t.set(r.name,o)}return t}function Gh(e,t){const r=new Map;for(const s of t){const o=e.get(s.filePath);o&&r.set(s.name,o)}return r}const qh=20;function Fl(e,t,r=qh){const s={};if(t.length===0||e.size===0)return s;const o=new Map;for(const p of t)o.set(p.name,p);const a=Vh(t),i=Gh(e,t);for(const[p,u]of i)s[p]={status:u};const l=new Map;for(const[p]of i)l.set(p,new Set([p]));const c=[];for(const[p]of i)c.push({name:p,depth:0});for(;c.length>0;){const{name:p,depth:u}=c.shift();if(u>=r)continue;const m=l.get(p)||new Set,h=a.get(p);if(h)for(const f of h){if(!o.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of m)y.has(x)||(y.add(x),g=!0);g&&c.push({name:f,depth:u+1})}}for(const[p,u]of l){if(i.has(p))continue;const m=[];for(const h of u){const f=o.get(h),y=i.get(h);f&&y&&m.push({name:h,filePath:f.filePath,changeType:y})}m.sort((h,f)=>h.name.localeCompare(f.name)),s[p]={status:"impacted",impactedBy:m.length>0?m:void 0}}return s}function Oa(e){var t,r;try{const s=F.join(e,".codeyam","config.json"),o=JSON.parse(K.readFileSync(s,"utf8"));if((t=o.defaultScreenSize)!=null&&t.width&&((r=o.defaultScreenSize)!=null&&r.height))return{width:o.defaultScreenSize.width,height:o.defaultScreenSize.height}}catch{}return null}async function Kh(e,t,r){const s=F.join(e,".codeyam","journal"),o=F.join(s,"index.json");F.join(s,"screenshots");let a;try{const l=await ve.readFile(o,"utf8");a=JSON.parse(l)}catch{return}let i=!1;for(const l of a.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let c=0;c<l.scenarioScreenshots.length;c++){const p=l.scenarioScreenshots[c];if(p.name!==t)continue;const u=F.join(s,p.path);try{await ve.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(m){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${m instanceof Error?m.message:m}`)}}i&&it.notifyChange("journal")}const Qh=vl;async function Zh({request:e}){var t;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const r=await e.json();r.url=r.url||r.path||void 0;const{name:s,description:o,componentName:a,componentPath:i}=r;if(!s)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=await Te();if(!l)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await $e(l),p=Me(),u=io();await p.insertInto("editor_scenarios").values({id:u,project_id:c.id,name:s,description:o||null,component_name:a||null,component_path:i||null,url:r.url||null,type:r.type||null,viewport_width:r.viewportWidth||null,viewport_height:r.viewportHeight||null}).execute();const m=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=r.type==="application"||r.type==="user";if(h&&r.seed){let E=r.seed;if(r.type==="user"&&r.baseScenario)try{const N=F.join(m,".codeyam","editor-scenarios",`${r.baseScenario}.json`),C=await ve.readFile(N,"utf-8"),A=JSON.parse(C);A.seed&&(E=Ah(A.seed,r.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${r.baseScenario}`))}catch(N){console.warn(`[editor-register-scenario] Could not read base scenario ${r.baseScenario}: ${N instanceof Error?N.message:N}`)}const k=F.join(m,".codeyam","editor-scenarios");await ve.mkdir(k,{recursive:!0}),await ve.writeFile(F.join(k,`${u}.json`),JSON.stringify({type:r.type,seed:E,...r.externalApis?{externalApis:r.externalApis}:{},...r.session?{session:r.session}:{}},null,2)),await ve.writeFile(F.join(k,`${u}.seed.json`),JSON.stringify(E,null,2))}else if(r.mockData){const E=F.join(m,".codeyam","editor-scenarios");await ve.mkdir(E,{recursive:!0}),await ve.writeFile(F.join(E,`${u}.json`),JSON.stringify(r.mockData,null,2))}let f=null;if(h&&r.seed){const E=Ao(m);if(E){const k=F.join(m,".codeyam","editor-scenarios",`${u}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${E}`);const N=await Eo(E,k);f={success:N.success,error:N.error},N.success?console.log(`[editor-register-scenario] Seed adapter completed in ${N.durationMs}ms`):console.warn(`[editor-register-scenario] Seed adapter failed: ${N.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${m}/.codeyam/seed-adapter.ts`),f={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}it.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${s}" (id: ${u})`);const y=r.url&&r.url.startsWith("/"),g=!r.url||y?await Al():null,x=Qh(),v=Ys(r.url||null,g,x);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${r.url||"none"}, isPath=${y}, proxy=${g||"none"}, devServer=${x||"none"} → using ${v||"none"}`);let b=null,w=null,S=[];if(v){const E=Ct(s),k=F.join(m,".codeyam","active-scenario.json");await ve.writeFile(k,JSON.stringify({scenarioId:u,scenarioSlug:E,type:r.type||null,timestamp:new Date().toISOString()})),Bn(),console.log(`[editor-register-scenario] Active scenario set to "${E}" (${u}), cache invalidated`),await new Promise(Y=>setTimeout(Y,500));const N=F.join(m,".codeyam","editor-scenarios","screenshots");await ve.mkdir(N,{recursive:!0});const C=F.join(N,`${u}.png`),A=Js(import.meta.url),T=await Hs(A,m);console.log(`[editor-register-scenario] Capture script: ${T}`);const P=Oa(m),_=JSON.stringify({url:v,outputPath:C,viewportWidth:r.viewportWidth||(P==null?void 0:P.width)||1280,viewportHeight:r.viewportHeight||(P==null?void 0:P.height)||720,...a?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Running Playwright capture: url=${v}, output=${C}`);const $=Date.now(),I=await Vs(T,_,m),R=Date.now()-$;if(console.log(`[editor-register-scenario] Capture ${I.success?"succeeded":"FAILED"} in ${R}ms`),I.success||(console.warn(`[editor-register-scenario] Capture stdout: ${I.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(I.error||"").slice(0,500)}`)),S=Pl(I.output),await _l(m,u,s,S),S.length>0&&console.warn(`[editor-register-scenario] ${S.length} client-side error(s) detected:`,S),I.success){b=`screenshots/${u}.png`;try{await p.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await p.updateTable("editor_scenarios").set({screenshot_path:b}).where("id","=",u).execute(),it.notifyChange("scenario"),await Kh(m,s,C)}else w=I.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${w}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${s}", screenshot=${b?"captured":"skipped"}`),v&&b)try{const E=pe()||process.cwd(),k=F.join(E,".codeyam","editor-step.json");let N=null;try{const C=K.readFileSync(k,"utf8");N=JSON.parse(C).featureStartedAt||null}catch{}if(N){const C=No(N),A=await p.selectFrom("editor_scenarios").selectAll().where("project_id","=",c.id).orderBy("created_at","asc").execute(),T=kt(A,_=>`${_.name}::${_.url||"/"}`),P=kn();if(P.length>0){let _=!1;try{const{execSync:j}=await import("child_process"),q=j("git rev-list --count HEAD",{cwd:E,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();_=parseInt(q,10)<=1}catch{_=!0}const $=Ol(P,_),I={},R=F.join(E,"app");if(K.existsSync(R)){const j=(q,V)=>{for(const U of K.readdirSync(q,{withFileTypes:!0}))if(U.name!=="isolated-components"){if(U.isDirectory())j(F.join(q,U.name),V?`${V}/${U.name}`:U.name);else if(U.name==="page.tsx"||U.name==="page.js"){const Z=nt(V?`/${V}`:"/");I[Z]=V?`app/${V}/${U.name}`:`app/${U.name}`}}};j(R,"")}let Y=[];try{await ze(),Y=await et({})||[]}catch{}const H=T.map(j=>({componentName:j.component_name||null,componentPath:j.component_path||null,url:j.url??null})),W=Ll(H,I,Y),B=Fl($,W),D=T.filter(j=>j.created_at<C),O=new Map;for(const j of D){const q=j.component_name||nt(j.url);((t=B[q])==null?void 0:t.status)==="impacted"&&O.set(q,j)}if(O.size>0){console.log(`[editor-register-scenario] Recapturing ${O.size} impacted older scenario(s): ${[...O.keys()].join(", ")}`);const j=Js(import.meta.url),q=await Hs(j,m),V=F.join(m,".codeyam","editor-scenarios","screenshots");for(const[Z,z]of O)try{const L=Ct(z.name);await Th({scenarioId:z.id,scenarioSlug:L,projectRoot:m}),Bn(),await new Promise(oe=>setTimeout(oe,300));const J=Ys(z.url||null,g,x);if(!J)continue;const G=F.join(V,`${z.id}.png`),X=Oa(m),le=JSON.stringify({url:J,outputPath:G,viewportWidth:z.viewport_width||(X==null?void 0:X.width)||1280,viewportHeight:z.viewport_height||(X==null?void 0:X.height)||720,...z.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Recapturing "${z.name}" (entity: ${Z})`);const xe=await Vs(q,le,m);xe.success?(await p.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${z.id}.png`}).where("id","=",z.id).execute(),console.log(`[editor-register-scenario] Recapture succeeded for "${z.name}"`)):console.warn(`[editor-register-scenario] Recapture failed for "${z.name}": ${xe.error}`)}catch(L){console.warn(`[editor-register-scenario] Recapture error for "${z.name}": ${L instanceof Error?L.message:L}`)}const U=F.join(m,".codeyam","active-scenario.json");await ve.writeFile(U,JSON.stringify({scenarioId:u,scenarioSlug:Ct(s),type:r.type||null,timestamp:new Date().toISOString()})),Bn(),it.notifyChange("scenario")}}}}catch(E){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${E instanceof Error?E.message:E}`)}try{const E=new Date().toISOString();Ph(m,{id:u,name:s,description:o||null,componentName:a||null,componentPath:i||null,url:r.url||null,mockDataFile:`editor-scenarios/${u}.json`,screenshotFile:b?`editor-scenarios/${b}`:null,createdAt:E,updatedAt:E})}catch(E){console.warn(`[editor-register-scenario] Failed to update manifest (non-blocking): ${E instanceof Error?E.message:E}`)}try{Po(r.url||void 0,u)}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:u,name:s,description:o,componentName:a||null,componentPath:i||null,screenshotPath:b,url:r.url||null,type:r.type||null,viewportWidth:r.viewportWidth||null,viewportHeight:r.viewportHeight||null},screenshotCaptured:b!==null,captureError:w,clientErrors:S,...f?{seedResult:f}:{}}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-register-scenario] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const Xh=Object.freeze(Object.defineProperty({__proto__:null,action:Zh},Symbol.toStringTag,{value:"Module"}));function ef({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const o=ae(i=>t.some(l=>l.flowId===i),[t]),a=ae(i=>{o(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,o]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=o(i.id),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>a(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!c&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&d("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((p,u)=>d("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:p.attributePath})," ",n("span",{className:"text-gray-400",children:p.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:p.value})]},u))})]})]},i.id)})})}function Mo(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const o=[];t.forEach(c=>{var u;const p=((u=c.metadata)==null?void 0:u.coveredFlows)||[];p.forEach(m=>{const h=s.get(m);h&&h.usedInScenarios.push({id:c.id||"",name:c.name})}),o.push({scenario:c,coveredFlowIds:p})});const a=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=a>0?i/a*100:0;return{executionFlows:r,totalFlows:a,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:o}}function tf(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const nf=({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 rf({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Wr(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(i=s.scenarios)==null?void 0:i.find(l=>l.name===Yr);if(!o)throw new Response("Default scenario not found",{status:404});const a=await Te();return Q({analysis:s,defaultScenario:o,entity:s.entity,entitySha:t,projectSlug:a})}function sf(){var B;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:o}=Ve(),a=Et(),{iframeRef:i}=Co(),[l,c]=M(""),[p,u]=M(400),[m,h]=M(!1),[f,y]=M(!1),[g,x]=M(!1),[v,b]=M(null),[w,S]=M(null),[E,k]=M([]),N=ne(()=>{var O;return!((O=e==null?void 0:e.metadata)!=null&&O.executionFlows)||!(e!=null&&e.scenarios)?[]:Mo(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:C,isStarting:A,isLoading:T,showIframe:P,iframeKey:_,onIframeLoad:$}=dn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:o,enabled:!0}),I=ae(async()=>{var D,O,j,q;if(!l.trim()&&E.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),S("Generating scenario with AI...");try{const V=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(D=e.metadata)==null?void 0:D.scenariosDataStructure,flowSelections:E.length>0?E:void 0})}),U=await V.json();if(!V.ok||!U.success)throw new Error(U.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",U.data);const Z=U.data;if(!Z.name||!Z.data)throw new Error("AI response missing required fields (name or data)");S("Saving new scenario..."),x(!0);const z={name:Z.name,description:Z.description||l,metadata:{data:Z.data,interactiveExamplePath:(O=t.metadata)==null?void 0:O.interactiveExamplePath}},L=[...e.scenarios||[],z],J=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:L})}),G=await J.json();if(!J.ok||!G.success)throw new Error(G.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",G);const X=(q=(j=G.analysis)==null?void 0:j.scenarios)==null?void 0:q.find(le=>le.name===Z.name);if(!(X!=null&&X.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),S("Scenario created! Redirecting..."),setTimeout(()=>void a(`/entity/${s}`),1e3);return}if(C){S("Capturing screenshot...");const le=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:C,scenarioId:X.id,projectId:e.projectId,viewportWidth:1440})}),xe=await le.json();!le.ok||!xe.success?(console.error("[CreateScenario] Capture failed:",xe),S("Scenario created! (Screenshot capture failed)")):S("Scenario created and captured!")}else S("Scenario created!");setTimeout(()=>{a(`/entity/${s}/scenarios/${X.id}`)},1e3)}catch(V){console.error("[CreateScenario] Error:",V),b(V instanceof Error?V.message:String(V)),S(null)}finally{y(!1),x(!1)}},[l,E,e,t,s,C,a]),R=f||g,Y=ae(()=>{h(!0)},[]),H=ae(D=>{if(!m)return;const O=D.clientX;O>=250&&O<=600&&u(O)},[m]),W=ae(()=>{h(!1)},[]);return te(()=>(m?(document.addEventListener("mousemove",H),document.addEventListener("mouseup",W)):(document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",W)),()=>{document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",W)}),[m,H,W]),d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void a(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),d("div",{className:"flex items-end gap-8 shrink-0",children:[n(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:d("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((B=e==null?void 0:e.scenarios)==null?void 0:B.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"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${p}px`},children:[d("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),N.length>0&&d("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[d("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",E.length>0&&d("span",{className:"text-blue-600",children:["(",E.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(ef,{executionFlows:N,selections:E,onChange:k,disabled:R})})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:D=>c(D.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:R})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void I(),disabled:R||!l.trim()&&E.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:R?"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})]})]}),d("div",{onMouseDown:Y,style:{width:"20px",position:"absolute",top:0,left:`${p-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:`
|
|
158
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
159
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
160
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
161
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
162
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(ts,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:C,isStarting:A,isLoading:T,showIframe:P,iframeKey:_,onIframeLoad:$,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const of=We(function(){return n(es,{children:n(sf,{})})}),af=Object.freeze(Object.defineProperty({__proto__:null,default:of,loader:rf,meta:nf},Symbol.toStringTag,{value:"Module"})),lf=vl;async function cf({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json(),{scenarioId:o,url:a,viewportWidth:i,viewportHeight:l}=s;if(!o)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const c=await Te();if(!c)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:p}=await $e(c),u=Me(),m=await u.selectFrom("editor_scenarios").selectAll().where("id","=",o).where("project_id","=",p.id).executeTakeFirst();if(!m)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const h=a??m.url??null,f=h&&h.startsWith("/"),y=!h||f?await Al():null,g=lf(),x=Ys(h,y,g);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${a||"none"}, db=${m.url||"none"}, proxy=${y||"none"}, devServer=${g||"none"} → captureUrl=${x||"none"}`),!x)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${m.name}" (id: ${o}), url: ${x}`);const v=process.env.CODEYAM_ROOT_PATH||process.cwd(),b=Ct(m.name),w=F.join(v,".codeyam","active-scenario.json");await ve.writeFile(w,JSON.stringify({scenarioId:o,scenarioSlug:b,timestamp:new Date().toISOString()})),Bn(),console.log(`[editor-capture-scenario] Active scenario set to "${b}", cache invalidated`),await new Promise(Y=>setTimeout(Y,500));const S=F.join(v,".codeyam","editor-scenarios","screenshots");await ve.mkdir(S,{recursive:!0});const E=F.join(S,`${o}.png`),k=Js(import.meta.url),N=await Hs(k,v);console.log(`[editor-capture-scenario] Capture script: ${N}`);let C=1280,A=720;try{const Y=F.join(v,".codeyam","config.json"),H=JSON.parse(K.readFileSync(Y,"utf8"));(t=H.defaultScreenSize)!=null&&t.width&&((r=H.defaultScreenSize)!=null&&r.height)&&(C=H.defaultScreenSize.width,A=H.defaultScreenSize.height)}catch{}const T=JSON.stringify({url:x,outputPath:E,viewportWidth:i||m.viewport_width||C,viewportHeight:l||m.viewport_height||A,...m.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Running Playwright capture: url=${x}, output=${E}`);const P=Date.now(),_=await Vs(N,T,v),$=Date.now()-P;if(console.log(`[editor-capture-scenario] Capture ${_.success?"succeeded":"FAILED"} in ${$}ms`),!_.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${_.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(_.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:_.error}),{status:500,headers:{"Content-Type":"application/json"}});const I=`screenshots/${o}.png`;try{await u.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await u.updateTable("editor_scenarios").set({screenshot_path:I}).where("id","=",o).execute();const R=Pl(_.output);return await _l(v,o,m.name,R),R.length>0&&console.warn(`[editor-capture-scenario] ${R.length} client-side error(s) detected:`,R),it.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:I,clientErrors:R}),{headers:{"Content-Type":"application/json"}})}catch(s){const o=s instanceof Error?s.message:String(s);return console.error("[editor-capture-scenario] Error:",s),new Response(JSON.stringify({error:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const df=Object.freeze(Object.defineProperty({__proto__:null,action:cf},Symbol.toStringTag,{value:"Module"}));async function uf({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","editor-scenarios","screenshots",t),o=ee.resolve(s),a=ee.resolve(ee.join(r,".codeyam","editor-scenarios","screenshots"));if(!o.startsWith(a))return new Response("Invalid path",{status:403});try{await we.access(s);const i=await we.readFile(s),l=ee.extname(s).toLowerCase(),c=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const pf=Object.freeze(Object.defineProperty({__proto__:null,loader:uf},Symbol.toStringTag,{value:"Module"}));async function mf({params:e,request:t}){const r=e["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),o=ee.join(s,".codeyam","journal","screenshots",r),a=ee.resolve(o),i=ee.resolve(ee.join(s,".codeyam","journal","screenshots"));if(!a.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await we.stat(o),c=`"${l.mtimeMs.toString(36)}-${l.size.toString(36)}"`;if(t.headers.get("if-none-match")===c)return new Response(null,{status:304,headers:{ETag:c}});const u=await we.readFile(o),m=ee.extname(o).toLowerCase(),h=m===".png"?"image/png":m===".jpg"||m===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":h,"Cache-Control":"public, max-age=0, must-revalidate",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const hf=Object.freeze(Object.defineProperty({__proto__:null,loader:mf},Symbol.toStringTag,{value:"Module"}));let Kt=null;async function ff({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:o,scenarioType:a}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=pe()||process.cwd(),l=ee.join(i,".codeyam"),c=ee.join(l,"active-scenario.json");let p=a||null;if(!p&&s){const f=ee.join(l,"editor-scenarios",`${s}.json`);try{fe.existsSync(f)&&(p=JSON.parse(fe.readFileSync(f,"utf-8")).type||null)}catch{}}fe.mkdirSync(l,{recursive:!0}),fe.writeFileSync(c,JSON.stringify({scenarioSlug:r,scenarioName:o||null,scenarioId:s||null,type:p,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let u=null;const m=p==="application"||p==="user";if(m&&s)if(Kt&&Kt.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),u=await Kt.promise;else{const f=Ao(i),y=ee.join(l,"editor-scenarios",`${s}.seed.json`);if(f&&fe.existsSync(y)){console.log(`[editor-switch-scenario] Running seed adapter for ${p} scenario "${o||r}"`);const g=Eo(f,y).then(x=>{const v={success:x.success,error:x.error};return x.success?console.log(`[editor-switch-scenario] Seed adapter completed in ${x.durationMs}ms`):console.warn(`[editor-switch-scenario] Seed adapter failed: ${x.error}`),v});Kt={scenarioId:s,promise:g};try{u=await g}finally{Kt&&Kt.scenarioId===s&&(Kt=null)}}else f||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),u={success:!1,error:"No seed adapter found"})}Bn();const h=Po();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:h,seeded:m,...u?{seedResult:u}:{}}),{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 gf=Object.freeze(Object.defineProperty({__proto__:null,action:ff},Symbol.toStringTag,{value:"Module"}));var ge;(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={}))})(ge||(ge={}));function zl(e,t){return e?Object.values(ge.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Bl=zl(process.env.DEFAULT_SMALLER_MODEL,ge.Model.OPENAI_GPT4_1_MINI),yf=zl(process.env.DEFAULT_LARGER_MODEL,ge.Model.OPENAI_GPT4_1),ut={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Ss={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},xf={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},ks={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},It={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},bf={[ge.Model.OPENAI_GPT5_1]:{id:ge.Model.OPENAI_GPT5_1,provider:ut,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ge.Model.OPENAI_GPT5]:{id:ge.Model.OPENAI_GPT5,provider:ut,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT5_MINI]:{id:ge.Model.OPENAI_GPT5_MINI,provider:ut,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT5_NANO]:{id:ge.Model.OPENAI_GPT5_NANO,provider:ut,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT4_1]:{id:ge.Model.OPENAI_GPT4_1,provider:ut,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ge.Model.OPENAI_GPT4_1_MINI]:{id:ge.Model.OPENAI_GPT4_1_MINI,provider:ut,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ge.Model.OPENAI_GPT4_O]:{id:ge.Model.OPENAI_GPT4_O,provider:ut,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ge.Model.OPENAI_GPT4_O_MINI]:{id:ge.Model.OPENAI_GPT4_O_MINI,provider:ut,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ge.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ge.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Ss,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ge.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ge.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Ss,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ge.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ge.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Ss,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ge.Model.OPENAI_GPT_OSS_120B_GROQ,provider:xf,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ge.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ge.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:It,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ge.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ge.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:It,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ge.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ge.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:It,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ge.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ge.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:It,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ge.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ge.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:It,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ge.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:ks,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ge.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:ks,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ge.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:ks,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ge.Model.PHIND_CODELLAMA]:{id:ge.Model.PHIND_CODELLAMA,provider:ut,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ge.Model.GOOGLE_GEMINI_PRO]:{id:ge.Model.GOOGLE_GEMINI_PRO,provider:It,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ge.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ge.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:It,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ge.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ge.Model.META_CODELLAMA_34B_INSTRUCT,provider:It,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ge.Model.OPENAI_GPT4_PREVIEW]:{id:ge.Model.OPENAI_GPT4_PREVIEW,provider:ut,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function ns(e){const t=bf[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function vf(e){return ns(e).maxCompletionTokens}function wf(e){return ns(e).pricing}const La=1e6;function Nf({model:e,usage:t}){const r=wf(e);return r?t.prompt_tokens*(r.input/La)+t.completion_tokens*(r.output/La):null}function Cf({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},o=Nf({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:o?Math.round(o*1e5)/1e5:void 0}}function Sf({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:o}){const a=r??Bl,i=ns(a);vf(a);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&o?{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Gs="/tmp/codeyam-e2e-tracking";let Es,As;function kf(){return Es===void 0&&(Es=process.env.CODEYAM_E2E_TRACK_DATA==="true"),Es}function Ef(){return As===void 0&&(As=!process.env.CODEYAM_LLM_FIXTURES_DIR),As}function Af(){K.existsSync(Gs)||K.mkdirSync(Gs,{recursive:!0})}function Pf(e){const t=JSON.stringify(e,null,0);return kd.createHash("md5").update(t).digest("hex")}function _f(e,t,r){return[e].join("_")+".json"}function Yl(e,t,r,s){if(!kf())return;Af();const o=_f(e),a=F.join(Gs,o),i=Pf(t);if(Ef()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};K.writeFileSync(a,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(a)){const l=JSON.parse(K.readFileSync(a,"utf-8")),c={matches:i===l.dataHash,firstRunHash:l.dataHash};if(c.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{c.differences=qs(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const p=a.replace(".json","_DIFF.json");K.writeFileSync(p,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${p}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function qs(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const o=Math.max(e.length,t.length);for(let a=0;a<o;a++)s.push(...qs(e[a],t[a],`${r}[${a}]`));return s}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),a=Object.keys(t),i=Array.from(new Set([...o,...a]));for(const l of i){const c=e[l],p=t[l];l in e?l in t?s.push(...qs(c,p,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const o=JSON.stringify(e),a=JSON.stringify(t);o.length<100&&a.length<100?s.push(`${r||"root"}: ${o} vs ${a}`):s.push(`${r||"root"}: values differ (${o.length} chars vs ${a.length} chars)`)}return s}co(lo);const lr=new Md({concurrency:100,timeout:1200*1e3,autoStart:!0}),Fa={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Dt={};async function Ks({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:o,model:a=Bl,attempts:i=0}){var N,C,A,T,P,_,$;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await jf(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${lr.size}, running=${lr.pending}]`);const l=Date.now();let c,p=0;const u=ns(a),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 h=new jd({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:a,responseType:o?"json_schema":s?"json_object":"text",jsonSchema:o},y=Sf(f),g=await lr.add(()=>(c=Date.now(),ba(async()=>{const I=Date.now(),R=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],Y=setInterval(()=>{const H=Math.floor((Date.now()-I)/1e3),W=Math.floor(H/10)%R.length;wa(1,`${R[W]} [type=${e}, model=${a}, elapsed=${H}s]`)},1e4);try{return await h.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(Y)}},{...Fa,onFailedAttempt:I=>{p++,console.log(`CodeYam Error: Completion call failed [model=${a}]`,{error:I,prompt:r,systemMessage:t,attempts:i,retryCount:p})}})));if(!g)throw new Error("Completion call returned no result");const x=g,v=Date.now(),b=Cf({chatRequest:f,chatCompletion:x,model:a});if(!b)throw new Error("Failed to get LLM call stats");b.retries=p,b.wait_ms=c-l,b.duration_ms=v-l;const w=(N=x.choices)==null?void 0:N[0];let S=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");S=(C=w.message)==null?void 0:C.content}let E=S;S&&(E=S.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=s?E&&(((A=E.match(/\{[\s\S]*\}/))==null?void 0:A[0])??E):E;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:S,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Ks({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:a,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(k.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:S,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(k)}catch(I){if(console.log("CodeYam Error: Invalid JSON in completion",{error:I.message,model:a,completion:k.substring(0,500),rawCompletion:S==null?void 0:S.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:I.message});const R=`Your previous response contained invalid JSON with the following error:
|
|
163
|
+
|
|
164
|
+
${I.message}
|
|
165
|
+
|
|
166
|
+
Here was your previous response:
|
|
167
|
+
\`\`\`
|
|
168
|
+
${k}
|
|
169
|
+
\`\`\`
|
|
170
|
+
|
|
171
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,Y=await lr.add(()=>ba(async()=>{const O=Date.now(),j=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],q=setInterval(()=>{const V=Math.floor((Date.now()-O)/1e3),U=Math.floor(V/10)%j.length;wa(1,`${j[U]} [type=${e}, model=${a}, elapsed=${V}s]`)},1e4);try{return await h.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:k},{role:"user",content:R}]},{timeout:300*1e3})}finally{clearInterval(q)}},{...Fa,onFailedAttempt:O=>{console.log("CodeYam Error: Correction call failed",{error:O,attempts:i})}}));if(!Y)throw new Error("Correction call returned no result");const H=Y,W=(_=(P=(T=H.choices)==null?void 0:T[0])==null?void 0:P.message)==null?void 0:_.content;let B=W;W&&(B=W.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const D=B&&((($=B.match(/\{[\s\S]*\}/))==null?void 0:$[0])??B);if(!D)throw new Error("Correction attempt returned empty completion");try{JSON.parse(D),console.log("CodeYam: JSON correction successful");const O=Date.now();return b.duration_ms=O-l,{finishReason:H.choices[0].finish_reason,completion:D,stats:b}}catch(O){return console.log("CodeYam Error: Corrected JSON still invalid",{error:O.message,correctedCompletion:D.substring(0,500)}),await Ks({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:a,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${I.message}`)}return Yl(`completionCall_${e}`,{completion:k,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:k,stats:b}}async function jf(e,t,r){var a,i,l,c,p;const s=await import("fs"),o=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const 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(o.join(t,b),"utf-8"),S=JSON.parse(w);m[S.prompt_type]||(m[S.prompt_type]=[]),m[S.prompt_type].push(S)}catch(w){console.warn(`Failed to parse LLM fixture file ${b}:`,w)}for(const b of Object.keys(m))m[b].sort((w,S)=>{const E=w.created_at??0,k=S.created_at??0;return E-k});const h=m[e];if(!h||h.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 S={};for(const k of h)try{const C=((a=JSON.parse(k.props||"{}").scenario)==null?void 0:a.name)||"__NO_SCENARIO__";S[C]||(S[C]=[]),S[C].push(k)}catch{}const E=S[w];if(E&&E.length>0){const k=`${t}::${e}::${w}`;Dt[k]===void 0&&(Dt[k]=0);const N=Dt[k];Dt[k]=(N+1)%E.length,f=E[N],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${w}' [${N+1}/${E.length}]`)}else{const k=Object.keys(S).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${w}'. Available: [${k}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;Dt[b]===void 0&&(Dt[b]=0);const w=Dt[b];Dt[b]=(w+1)%h.length,f=h[w],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${w+1}/${h.length}]`)}let g;try{g=((c=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:c.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((p=x.match(/\{[\s\S]*\}/))==null?void 0:p[0])??x);return Yl(`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 za(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Mf(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),o=io(),a=Date.now(),i={...r,id:o,created_at:a,props:s};let l;const c=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?l=F.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=F.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const u=F.dirname(l);return await ve.mkdir(u,{recursive:!0}),await ve.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:o}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const p=za();if(!p)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 ${o} property ${u} with explicit value 'undefined'`);try{return await new zr().send(new Td({TableName:za(),Item:Rd(i,{removeUndefinedValues:!0})})),{id:o}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${p}`,u),{id:"-1"}}}new zr({});new zr({});new zr({});const Tf=3,$f=2,To=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Tf*String(t).length*(1+$f)});new po(To());new po(To());new po(To());class Rf{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 If{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Df{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Of{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Lf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ff{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];if(s.addType(a,"function"),s.addEquivalence(a.withParameter(1),r.withElement("*")),o.args.length>1){const i=o.args[1];s.addEquivalence(a.withParameter(0),i)}}}isComplete(){return!0}}class zf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const o=t.getLastFunctionCallSegment();o&&o.args.forEach(a=>{s.addEquivalence(t,a)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Bf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const o=t.withReturnValues();s.addType(o,"unknown")}isComplete(){return!0}}class Yf{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let a=2;a<o.args.length;a++){const i=o.args[a];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Uf{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let a=0;a<o.args.length;a++)s.addEquivalence(r.withElement("*"),t.withParameter(a))}isComplete(){return!0}}class Wf{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addEquivalence(t.withParameter(0),a)}}isComplete(){return!0}}class Jf{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Hf{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Vf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Gf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class qf{getReturnType(){return"object"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"array")}}isComplete(){return!0}}class Kf{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 Qf{getReturnType(){return"unknown"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const a=o.args[0];s.addType(a,"function"),s.addEquivalence(a.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),a.withProperty("returnValue"))}}isComplete(){return!0}}class Zf{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Xf{getReturnType(){return"array"}addEquivalences(t,r,s){const o=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),o&&o.args.length>0){const a=o.args[0];s.addEquivalence(t.withParameter(0),a)}}isComplete(){return!0}}function eg(){const e=new Rf;return e.register("filter",new If,"Array"),e.register("map",new Jf,"Array"),e.register("flatMap",new Hf,"Array"),e.register("join",new Wf,"Array"),e.register("find",new Lf,"Array"),e.register("findLast",new Gf,"Array"),e.register("at",new Vf,"Array"),e.register("reduce",new Ff,"Array"),e.register("concat",new zf,"Array"),e.register("slice",new Bf,"Array"),e.register("splice",new Yf,"Array"),e.register("push",new Uf,"Array"),e.register("some",new Df,"Array"),e.register("every",new Of,"Array"),e.register("fromEntries",new qf,"Object"),e.register("split",new Kf,"String"),e.register("then",new Qf,"Promise"),e.register("useState",new Xf,"React"),e.register("useMemo",new Zf,"React"),e}eg();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 tg=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),ng=new Set(["find","findLast","at","pop","shift"]),rg=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),sg=new Set([...tg,...ng,...rg]),og=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),ag=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),ig=new Set([...og,...ag]);[...sg,...ig];class lg{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const o=" ".repeat(this.depth),a=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${a}${o}${r}`,JSON.stringify(s)):console.info(`${a}${o}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new lg({enabled:!1});function Qt(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),o=new Set(Object.keys(t??{}));for(const a of o)s.has(a)||(r.added[a]=t[a]);for(const a of s)o.has(a)||(r.removed[a]=e[a]);for(const a of s)o.has(a)&&e[a]!==t[a]&&(r.changed[a]={from:e[a],to:t[a]});return r}function cg(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function cr(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let dg=0;class $o{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++dg,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var c,p,u,m;if(!this.isEnabled())return;const o=this.traces.get(t);if(!o)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const a=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:a},l=o.stages[o.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:Qt(l.data.signatureSchema,a.signatureSchema),returnValueSchema:Qt(l.data.returnValueSchema,a.returnValueSchema)},a.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const h=new Set([...Object.keys(a.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of h){const y=(c=l.data.dependencySchemas)==null?void 0:c[f],g=(p=a.dependencySchemas)==null?void 0:p[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,S=Qt(b,w);cg(S)&&(i.diffFromPrevious.dependencySchemas[v]=S)}}}o.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var o;const t={},r=new Map;for(const[a,i]of this.traces){let l=0;for(const c of i.stages){if(!c.diffFromPrevious)continue;const u=`${((o=i.stages[i.stages.indexOf(c)-1])==null?void 0:o.stage)??"start"}→${c.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const m=c.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,l+=cr(m)}if(c.diffFromPrevious.returnValueSchema){const m=c.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,l+=cr(m)}}r.set(a,l)}const s=[...r.entries()].sort((a,i)=>i[1]-a[1]).slice(0,10).map(([a])=>a);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(p=>`${p}(${this.traces.get(p).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:o}=this.computeFlushSummary(),a={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:o},l=F.dirname(this.outputPath);K.existsSync(l)||K.mkdirSync(l,{recursive:!0});const c=K.openSync(this.outputPath,"w");try{K.writeSync(c,`{
|
|
172
|
+
"meta": `),K.writeSync(c,JSON.stringify(a,null,2)),K.writeSync(c,`,
|
|
173
|
+
"summary": `),K.writeSync(c,JSON.stringify(i,null,2)),K.writeSync(c,`,
|
|
174
|
+
"entities": {`);let p=!0;for(const[u,m]of this.traces)p||K.writeSync(c,","),K.writeSync(c,`
|
|
175
|
+
${JSON.stringify(u)}: `),K.writeSync(c,JSON.stringify(m,null,2)),p=!1;K.writeSync(c,`
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{K.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r),o=new $o({enabled:!1});o.projectSlug=s.meta.projectSlug;for(const[a,i]of Object.entries(s.entities))o.traces.set(a,i);return o}getSummary(){var o,a,i;const t={},r=new Map;for(const[l,c]of this.traces){let p=0;for(let u=1;u<c.stages.length;u++){const m=c.stages[u],f=`${((o=c.stages[u-1])==null?void 0:o.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(a=m.diffFromPrevious)!=null&&a.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,p+=cr(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,p+=cr(y)}}r.set(l,p)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(o=>o.path&&r.test(o.path)):s.operations:[]}tracePath(t,r){var a,i;const s=this.traces.get(t),o=[];if(!s)return{entityName:t,path:r,history:o};for(const l of s.stages){const c=(a=l.data.signatureSchema)==null?void 0:a[r],p=(i=l.data.returnValueSchema)==null?void 0:i[r],u=c??p;u!==void 0&&o.push({stage:l.stage,value:u})}for(const l of s.operations)l.path===r&&o.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:o}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const o=[],a=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,c]of Object.entries(i.data.signatureSchema??{}))a.test(l)&&o.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))a.test(l)&&o.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[p,u]of Object.entries(c))for(const[m,h]of Object.entries(u.returnValueSchema??{}))a.test(m)&&o.push({stage:i.stage,path:`${l}/${p}::${m}`,type:h,schemaType:"dependency"})}return o}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const o=new Set(["length","toString","valueOf","constructor"]),a=new Map,i=(c,p)=>{const u=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],h=u[2]==="[]";if(o.has(m))return;const f=m+(h?"[]":"");a.has(f)||a.set(f,[]),a.get(f).push({path:c,type:p})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,p]of Object.entries(c))for(const[u,m]of Object.entries(p.returnValueSchema??{}))i(u,m);const l=[];for(const[c,p]of a)new Set(p.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:p.map(m=>({...m,stage:s.stage}))});return l.sort((c,p)=>{const u=new Set(c.paths.map(h=>h.type)).size;return new Set(p.paths.map(h=>h.type)).size-u}),l}getStageDiffSummary(t,r,s){const o=this.traces.get(t);if(!o)return null;const a=o.stages.find(h=>h.stage===r),i=o.stages.find(h=>h.stage===s);if(!a||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=a.data.returnValueSchema??{},p=i.data.returnValueSchema??{},u=new Set(Object.keys(c)),m=new Set(Object.keys(p));for(const h of m)u.has(h)?c[h]!==p[h]&&l.typeChanged.push({path:h,from:c[h],to:p[h]}):l.added.push(`${h}: ${p[h]}`);for(const h of u)m.has(h)||l.removed.push(`${h}: ${c[h]}`);return l}traceSchemaTransform(t,r,s,o,a){if(!this.enabled)return o(s),s;const i={...s};o(s);const l=Qt(i,s);for(const[c,p]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:p,context:{...a,changeType:"added"}});for(const[c,p]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:p,after:void 0,context:{...a,changeType:"removed"}});for(const[c,{from:p,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:p,after:u,context:{...a,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,o,a){if(!this.enabled)return;const i=Qt(s,o);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...a,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...a,changeType:"removed"}});for(const[l,{from:c,to:p}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:p,context:{...a,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,o,a="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const c=s[i][l];(a==="signature"||a==="both")&&c.signatureSchema&&o(c.signatureSchema),(a==="returnValue"||a==="both")&&c.returnValueSchema&&o(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],p={filePath:i,dependencyName:l};(a==="signature"||a==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,o,{...p,schemaType:"signature"}),(a==="returnValue"||a==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,o,{...p,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,o){var i;if(!this.enabled){o();return}const a={};for(const l in s){a[l]={};for(const c in s[l]){const p=s[l][c];a[l][c]={sig:{...p.signatureSchema||{}},rv:{...p.returnValueSchema||{}}}}}o();for(const l in s)for(const c in s[l]){const p=s[l][c],u=(i=a[l])==null?void 0:i[c],m={filePath:l,dependencyName:c};if(p.signatureSchema){const h=(u==null?void 0:u.sig)||{},f=Qt(h,p.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(p.returnValueSchema){const h=(u==null?void 0:u.rv)||{},f=Qt(h,p.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 ug(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const Ba=new $o({enabled:ug(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{Ba.isEnabled()&&Ba.flush()});function Ul(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 $d.parse(e)}catch(r){const o=r.message.match(/invalid character .* at (\d+):(\d+)/);if(o){const a=parseInt(o[2],10);if(e.substring(a-2,a-1)==='"')return e=e.substring(0,a-2)+"\\"+e.substring(a-2),Ul(e)}return null}}function pg({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let o="";return s&&s.length>0&&(o=`
|
|
179
|
+
User-selected Execution Flow Values:
|
|
180
|
+
The user has specifically requested these values be used in the scenario:
|
|
181
|
+
${s.map(a=>` - ${a.path}: ${a.value}${a.isCustom?" (custom value)":""}`).join(`
|
|
182
|
+
`)}
|
|
183
|
+
|
|
184
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
185
|
+
`),`Mock Scenario Data Structure:
|
|
186
|
+
\`\`\`
|
|
187
|
+
${JSON.stringify(r,null,2)}
|
|
188
|
+
\`\`\`
|
|
189
|
+
Existing Mock Scenario Data:
|
|
190
|
+
\`\`\`
|
|
191
|
+
${JSON.stringify(t,null,2)}
|
|
192
|
+
\`\`\`
|
|
193
|
+
${o}
|
|
194
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
195
|
+
`}function mg({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o}){const a=s.find(i=>i.name===Yr);return`Mock Scenario Data Structure:
|
|
196
|
+
\`\`\`
|
|
197
|
+
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
198
|
+
\`\`\`
|
|
199
|
+
|
|
200
|
+
Existing Mock Scenario Data:
|
|
201
|
+
\`\`\`
|
|
202
|
+
${JSON.stringify(s.map(i=>({name:i.name,data:Ln(a.metadata.data,i.metadata.data)})),null,2)}
|
|
203
|
+
\`\`\`
|
|
204
|
+
|
|
205
|
+
Mock Scenario that should be edited: "${t}"
|
|
206
|
+
${r?`The portion of the data that should be edited:
|
|
207
|
+
\`\`\`
|
|
208
|
+
${JSON.stringify(r,null,2)}
|
|
209
|
+
\`\`\``:""}
|
|
210
|
+
|
|
211
|
+
How this data should be changed: "${e}"
|
|
212
|
+
`}async function hg({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o,flowSelections:a,model:i}){const l=t?mg({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o}):pg({description:e,existingScenarios:s,scenariosDataStructure:o,flowSelections:a}),c=await Ks({type:"guessScenarioDataFromDescription",systemMessage:t?gg(r):fg,prompt:l,model:i??yf});await Mf({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:o,model:i},...c.stats});const{completion:p}=c;return p?Ul(p):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const fg=`
|
|
213
|
+
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.
|
|
214
|
+
|
|
215
|
+
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.
|
|
216
|
+
|
|
217
|
+
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.
|
|
218
|
+
|
|
219
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
220
|
+
\`\`\`
|
|
221
|
+
export type ScenarioData = {
|
|
222
|
+
name: string;
|
|
223
|
+
description: string;
|
|
224
|
+
data: {
|
|
225
|
+
mockData: { [key: string]: unknown };
|
|
226
|
+
argumentsData: { [key: string]: unknown };
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
\`\`\`
|
|
231
|
+
`,gg=e=>`
|
|
232
|
+
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.
|
|
233
|
+
|
|
234
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
235
|
+
${e?`
|
|
236
|
+
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.`:""}
|
|
237
|
+
|
|
238
|
+
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.
|
|
239
|
+
|
|
240
|
+
You must respond with valid JSON following this type definition:
|
|
241
|
+
\`\`\`
|
|
242
|
+
{
|
|
243
|
+
data: {
|
|
244
|
+
mockData: { [key: string]: unknown };
|
|
245
|
+
argumentsData: { [key: string]: unknown };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
\`\`\`
|
|
249
|
+
`;async function yg({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:o,editingMockName:a,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return Q({error:"Missing required field: description or flowSelections"},{status:400});const c=await hg({description:r||"",existingScenarios:s??[],scenariosDataStructure:o,editingMockName:a,editingMockData:i,flowSelections:l}),p=(c==null?void 0:c.data)||c;return Q({success:!0,data:p})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),Q({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const xg=Object.freeze(Object.defineProperty({__proto__:null,action:yg},Symbol.toStringTag,{value:"Module"}));function bg(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],o=new Date(r);o.setDate(o.getDate()-s);const a=o.toISOString().split("T")[0],i=e.filter(m=>m.date>=a),l=new Set(i.map(m=>m.commitSha).filter(Boolean)),c=new Map;for(const m of i)if(m.scenarioScreenshots)for(const h of m.scenarioScreenshots){c.has(h.name)||c.set(h.name,[]);const f=c.get(h.name);f.some(y=>y.path===h.path)||f.push({path:h.path,time:m.time})}for(const m of c.values())m.sort((h,f)=>h.time.localeCompare(f.time));const p=[],u=new Map;for(const[m,h]of c){const f=m.indexOf(" - ");if(f!==-1){const y=m.slice(0,f);u.has(y)||u.set(y,[]),u.get(y).push({name:m,screenshots:h})}else p.push({name:m,screenshots:h})}return{commitCount:l.size,entryCount:i.length,appScenarios:p,componentGroups:u,totalScenarios:c.size}}function vg(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function wg(e){const t=new Map;for(const r of e){let s;if("componentName"in r&&r.componentName)s=r.componentName;else if("componentName"in r&&r.componentName===null)s="App";else{const a=r.name.indexOf(" - ");s=a!==-1?r.name.slice(0,a):"App"}const o=t.get(s)||[];o.push(r),t.set(s,o)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function Ng(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function Cg(e){const{title:t,timeStr:r,type:s,description:o,allScenarioNames:a,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:p,featureName:u,userPrompt:m}=e,h=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&h.push(`**Feature:** ${u}`),m&&h.push(`**Prompt:** ${m}`),a.length>0&&h.push(`**Scenarios:** ${a.join(", ")}`),h.push(""),h.push(o),i&&(h.push(""),h.push(``)),l.length>0){h.push(""),h.push("**Scenario Screenshots:**");for(const f of l)h.push(""),h.push(``)}return c&&p&&(h.push(""),h.push(`**Commit:** \`${c}\` — ${p}`)),h.push(""),h.join(`
|
|
250
|
+
`)}function Sg(e,t){return e.findIndex(r=>r.time===t)}function kg(e){return!!e.commitSha}function Eg(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function Ag(e,t,r,s){const o=`
|
|
251
|
+
**Commit:** \`${r}\` — ${s||"no message"}
|
|
252
|
+
`,a=`### ${t}`,i=e.lastIndexOf(a);if(i===-1)return null;const l=e.indexOf(`
|
|
253
|
+
---
|
|
254
|
+
`,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+o+e.slice(c)}async function Pg(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Te();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await $e(t),o=await Me().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${o.length} matching scenarios:`,o.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const a=o.filter(c=>!c.screenshot_path);a.length>0&&console.warn(`[editorScenarioLookup] ${a.length} scenarios have no screenshot_path:`,a.map(c=>c.name));const i=o.filter(c=>c.screenshot_path),l=kt(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,url:c.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function _g(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Te();if(!t)return[];const{project:r}=await $e(t),o=await Me().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),a=new Set(e),l=o.filter(p=>{const u=jo({componentName:p.component_name,url:p.url});return a.has(u)}).filter(p=>p.screenshot_path),c=kt(l,p=>p.name).map(p=>({name:p.name,screenshotPath:p.screenshot_path,scenarioId:p.id,componentName:p.component_name||null,url:p.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function Wl(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Te();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await $e(t),s=Me(),o=pe()||process.cwd();let a=null;const i=F.join(o,".codeyam","editor-step.json");try{const h=K.readFileSync(i,"utf8");a=JSON.parse(h).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!a)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>a?e:a,c=No(l),p=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${p.length} scenarios since ${l}`);const u=p.filter(h=>h.screenshot_path),m=kt(u,h=>h.name).map(h=>({name:h.name,screenshotPath:h.screenshot_path,scenarioId:h.id,componentName:h.component_name||null,url:h.url||null}));return console.log(`[editorScenarioLookup] Found ${m.length} session scenarios with screenshots`),m}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function Qs(e,t,r){const s=F.join(t,".codeyam","journal","screenshots");await ve.mkdir(s,{recursive:!0});const o=[];for(const a of e){const i=F.join(t,".codeyam","editor-scenarios",a.screenshotPath),l=Ng(a.name,r),c=F.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${a.name}" from ${i} → ${c}`);try{await ve.access(i),await ve.copyFile(i,c),o.push({name:a.name,path:`screenshots/${l}`,componentName:a.componentName,url:a.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${a.name}"`)}catch(p){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,p instanceof Error?p.message:p)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${o.length} scenarios have screenshots embedded`),o}async function jg({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:o,description:a,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=F.join(l,".codeyam","journal"),p=F.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const g=await ve.readFile(p,"utf8");u=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const m=Sg(u.entries,r);if(m===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const h=u.entries[m];if(kg(h))return console.log(`[editor-journal-update] Rejected: entry "${h.title}" already committed (${h.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${h.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await Wl();g.length>0&&(f=g.map(x=>x.name),y=await Qs(g,l,new Date))}if(Eg(h,{commitSha:s,commitMessage:o,description:a,scenarios:f,scenarioScreenshots:y}),u.entries[m]=h,await ve.writeFile(p,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=h.date,x=F.join(c,`${g}.md`);let v="";try{v=await ve.readFile(x,"utf8")}catch{}if(v){const b=Ag(v,h.title,s,o||null);b&&(await ve.writeFile(x,b,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return it.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${h.title}"`),new Response(JSON.stringify({success:!0,entry:h}),{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 Mg=Object.freeze(Object.defineProperty({__proto__:null,action:jg},Symbol.toStringTag,{value:"Module"}));async function Tg({request:e}){try{const t=process.env.CODEYAM_ROOT_PATH||process.cwd(),r=await jl(t);let s=0;const o={};for(const[a,i]of Object.entries(r))i.errors.length>0&&(o[a]=i,s+=i.errors.length);return new Response(JSON.stringify({hasErrors:s>0,totalErrors:s,scenarios:o}),{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 $g=Object.freeze(Object.defineProperty({__proto__:null,loader:Tg},Symbol.toStringTag,{value:"Module"}));async function Rg({request:e}){try{const r=(await cn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],c=l.scenarios||[],p=!((y=l.status)!=null&&y.finishedAt),u=i.entityType||"visual",h=u==="library"||u==="functionCall"?c.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):c.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=c.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:h,isAnalyzing:p,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),o=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),a=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:o,analyzing:a}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ig=Object.freeze(Object.defineProperty({__proto__:null,loader:Rg},Symbol.toStringTag,{value:"Module"}));function Dg(e){const t={},r=F.join(e,"app");if(!K.existsSync(r))return t;const s=l=>l.split("/").filter(c=>!c.startsWith("(")).join("/"),o=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),a=new Set([".tsx",".ts",".jsx",".js"]),i=(l,c)=>{for(const p of K.readdirSync(l,{withFileTypes:!0}))if(p.name!=="isolated-components")if(p.isDirectory())i(F.join(l,p.name),c?`${c}/${p.name}`:p.name);else if(p.name==="page.tsx"||p.name==="page.js"){const u=c?`app/${c}/${p.name}`:`app/${p.name}`,m=s(c);t[nt(m?`/${m}`:"/")]=u}else{if(o.has(p.name))continue;{const u=F.extname(p.name);if(!a.has(u))continue;const m=F.basename(p.name,u),h=c?`app/${c}/${p.name}`:`app/${p.name}`,f=s(c);let y;m==="index"?y=f?`/${f}`:"/":y=f?`/${f}/${m}`:`/${m}`;const g=nt(y);t[g]||(t[g]=h)}}};return i(r,""),t}function Og(e){try{const t=Ae("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function Lg(e){try{const t=F.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function Jl(e){try{const t=F.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function Hl(e){try{const t=F.join(e,".codeyam","editor-user-prompt.txt");return K.readFileSync(t,"utf8").trim()||null}catch{return null}}async function rs(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,o=Dg(t),a=new Set(Object.keys(o)),i=kn();if(i.length===0)return{entityChangeStatus:{},pageEntityNames:a};const l=Og(t),c=Ol(i,l);let p=[];try{await ze(),p=await et({})||[]}catch{}const u=Ll(r,o,p);let m=u;if(s&&s.length>0){const f=new Set(u.map(g=>g.name)),y=Wh(s,f);m=[...u,...y]}return{entityChangeStatus:Fl(c,m),pageEntityNames:a}}async function Fg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:o,scenarios:a,includeSessionScenarios:i,screenshot:l,commitSha:c,commitMessage:p}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(a||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!o)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!o}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=F.join(u,".codeyam","journal");await ve.mkdir(m,{recursive:!0});const h=new Date,f=h.toISOString().split("T")[0],y=h.toISOString();let g=a||[];const x=F.join(m,"index.json");let v={entries:[]};try{const R=await ve.readFile(x,"utf8");v=JSON.parse(R)}catch{}let b;i&&v.entries.length>0&&(b=v.entries[v.entries.length-1].time);const w=i?await Wl(b):a&&a.length>0?await Pg(a):[];i&&w.length>0&&(g=w.map(R=>R.name));const S=await Qs(w,u,h);let E;try{const R=pe()||process.cwd(),Y=await Te();if(Y){const{project:H}=await $e(Y),B=await Me().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",H.id).orderBy("created_at","asc").execute(),O=kt(B,q=>`${q.name}::${q.url||"/"}`).map(q=>({componentName:q.component_name||null,componentPath:q.component_path||null,url:q.url??null})),j=await rs({projectRoot:R,scenarioInputs:O});Object.keys(j.entityChangeStatus).length>0&&(E=j.entityChangeStatus)}}catch{}if(E&&Object.keys(E).length>0){const R=new Set(w.map(H=>H.name)),Y=Object.entries(E).filter(([,H])=>H.status==="impacted").map(([H])=>H);if(Y.length>0){const H=[],W=new Set(w.map(B=>jo(B)));for(const B of Y)W.has(B)||H.push(B);if(H.length>0)try{const B=await _g(H);if(B.length>0){const D=await Qs(B.filter(O=>!R.has(O.name)),u,h);S.push(...D),g.push(...D.map(O=>O.name))}}catch{}}}let k=S,N=g;if(!i&&E&&Object.keys(E).length>0){k=Hh(S,E);const R=new Set(k.map(Y=>Y.name));N=g.filter(Y=>R.has(Y))}const C=Jl(u),A=Hl(u);let T;try{const R=kn();R.length>0&&(T=R.filter(Y=>Y.status!=="deleted").map(Y=>({path:Y.path,status:Y.status})))}catch{}const P=F.join(m,`${f}.md`);let _="";try{_=await ve.readFile(P,"utf8")}catch{_=`# Development Journal — ${f}
|
|
255
|
+
`}const $=Cg({title:r,timeStr:y,type:s,description:o,allScenarioNames:N,screenshot:l||null,scenarioScreenshots:k,commitSha:c||null,commitMessage:p||null,featureName:C,userPrompt:A});await ve.writeFile(P,_+$,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${P}`);const I={date:f,time:y,title:r,type:s,description:o,scenarios:N,screenshot:l||null,scenarioScreenshots:k,commitSha:c||null,commitMessage:p||null,entityChangeStatus:E,featureName:C,userPrompt:A,modifiedFiles:T};return v.entries.push(I),await ve.writeFile(x,JSON.stringify(v,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${v.entries.length} entries)`),it.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${k.length}`),new Response(JSON.stringify({success:!0,entry:I,scenarioScreenshotsFound:k.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 zg=Object.freeze(Object.defineProperty({__proto__:null,action:Fg},Symbol.toStringTag,{value:"Module"}));function Bg({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=pe()||process.cwd();let a=new URL(e.url).searchParams.get("scenarioId");if(!a){const c=F.join(r,".codeyam","active-scenario.json");if(!K.existsSync(c))return new Response(JSON.stringify({}),{headers:t});a=JSON.parse(K.readFileSync(c,"utf-8")).scenarioId||null}if(!a)return new Response(JSON.stringify({}),{headers:t});const i=F.join(r,".codeyam","editor-scenarios",`${a}.json`);if(!K.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=K.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const Yg=Object.freeze(Object.defineProperty({__proto__:null,loader:Bg},Symbol.toStringTag,{value:"Module"}));async function Ug(e,t){const r=pe();if(!r)return{entityCalls:[],analysisCalls:[]};const s=F.join(r,".codeyam","llm-calls");try{await ve.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],a=[];try{const l=(await ve.readdir(s)).filter(v=>v.endsWith(".json")),c=`${e}_`,p=t?`${t}_`:null,u=[],m=[];for(const v of l)v.startsWith(c)||p&&v.startsWith(p)?u.push(v):m.push(v);const h=u.map(async v=>{try{const b=F.join(s,v),w=await ve.readFile(b,"utf-8");return JSON.parse(w)}catch{return null}}),f=m.map(async v=>{try{const b=F.join(s,v),w=await ve.readFile(b,"utf-8"),S=JSON.parse(w);return S.object_id===e||t&&S.object_id===t?S:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(h),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?o.push(v):t&&v.object_id===t&&a.push(v);o.sort((v,b)=>b.created_at-v.created_at),a.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:a}}async function Wg({params:e,request:t}){const{entitySha:r}=e;if(!r)return Q({error:"Entity SHA is required"},{status:400});const o=new URL(t.url).searchParams.get("analysisId")||void 0,a=await Ug(r,o);return Q(a)}const Jg=Object.freeze(Object.defineProperty({__proto__:null,loader:Wg},Symbol.toStringTag,{value:"Module"}));async function Hg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=pe()||process.cwd(),r=ee.join(t,".codeyam","config.json");if(!fe.existsSync(r))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const s=await e.json(),o=JSON.parse(fe.readFileSync(r,"utf8"));return s.projectTitle!==void 0&&(o.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(o.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(o.defaultScreenSize=s.defaultScreenSize),fe.writeFileSync(r,JSON.stringify(o,null,2)),it.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:o.projectTitle||null,projectDescription:o.projectDescription||null,defaultScreenSize:o.defaultScreenSize||null}),{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 Vg=Object.freeze(Object.defineProperty({__proto__:null,action:Hg},Symbol.toStringTag,{value:"Module"}));function Gg(e){try{const t=F.join(e,"package.json"),r=JSON.parse(K.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function qg(e,t){var i;const s=JSON.parse(t).testResults||[],o=[];for(const l of s)for(const c of l.assertionResults||[]){const p=c.ancestorTitles||[],u=c.title||c.fullName||"unknown",m=p.length>0?`${p.join(" > ")} > ${u}`:u;o.push({title:u,fullName:m,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const a=o.some(l=>l.status==="failed");return{testFilePath:e,status:a?"failed":"passed",testCases:o}}async function Vl(e,t){const r=Gg(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=F.isAbsolute(t)?t:F.join(e,t);if(!K.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const o=F.join(ao.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(a=>{var m;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",o,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",o,"--testPathPatterns",t]);const c=At(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(m=c.stderr)==null||m.on("data",h=>{p+=h.toString()});const u=setTimeout(()=>{c.kill("SIGTERM"),a({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(u);try{const h=K.readFileSync(o,"utf8");K.unlinkSync(o),a(qg(t,h))}catch{a({testFilePath:t,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",h=>{clearTimeout(u),a({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${h.message}`})})})}async function Kg({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=pe()||process.cwd();try{const o=await Vl(s,r);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}catch(o){const a=o instanceof Error?o.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:a}),{status:500,headers:{"Content-Type":"application/json"}})}}const Qg=Object.freeze(Object.defineProperty({__proto__:null,loader:Kg},Symbol.toStringTag,{value:"Module"}));function Ya(e,t){var r,s;try{return((s=(r=Ae(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(o){return console.error(`Failed to get commit SHA for ${e}:`,o),""}}function Zg(e,t,r,s){const o=qn.createHash("sha256");return o.update(`${e}:${t}:${r}:${s}`),o.digest("hex").substring(0,16)}function Gl(){const e=pe();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function Xg(e){try{const t=Gl(),r=ee.join(t,`${e}.json`);if(!fe.existsSync(r))return null;const s=fe.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function e0(e,t){try{const r=Gl(),s=ee.join(r,`${e}.json`);fe.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function t0(e,t,r){const s=Er(t,e),o=Er(r,e),a=new Map(s.map(u=>[u.name,u])),i=new Map(o.map(u=>[u.name,u])),l=[],c=[],p=[];for(const[u,m]of i){const h=a.get(u);h?h.sha!==m.sha&&c.push({name:u,baseSha:h.sha,compareSha:m.sha,entityType:m.entityType}):l.push(m)}for(const[u,m]of a)i.has(u)||p.push(m);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:p}}function n0(e,t){const r=pe();if(!r)throw new Error("No project root found");const s=Ya(e,r),o=Ya(t,r);if(!s||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const a=Zg(e,t,s,o),i=Xg(a);if(i)return console.log(`Using cached branch entity diff: ${a}`),i;const l=Il(e,t),c=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=gr(u.path,e,t),h=Er(m.oldContent,u.path);c.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:h})}else if(u.status==="added"){const m=gr(u.path,e,t),h=Er(m.newContent,u.path);c.push({filePath:u.path,newEntities:h,modifiedEntities:[],deletedEntities:[]})}else{const m=gr(u.path,e,t),h=t0(u.path,m.oldContent,m.newContent);(h.newEntities.length>0||h.modifiedEntities.length>0||h.deletedEntities.length>0)&&c.push(h)}const p={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:o,fileComparisons:c,cacheKey:a,computedAt:new Date().toISOString()};return e0(a,p),p}function r0({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return Q({error:"Missing required parameters: base and compare"},{status:400});const o=n0(r,s);return Q(o)}catch(t){return console.error("Failed to compute branch entity diff:",t),Q({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const s0=Object.freeze(Object.defineProperty({__proto__:null,loader:r0},Symbol.toStringTag,{value:"Module"}));async function o0({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:o,viewportWidth:a=1440}=t;if(!r||!s||!o)return Q({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=pe();if(!i)return Q({error:"Project root not found"},{status:500});const l=F.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:o,projectRoot:i,viewportWidth:a}),p=await new Promise(h=>{const f=F.join(i,".codeyam","db.sqlite3"),y=At("npx",["tsx",l,c],{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 S of w)S.includes("[Capture]")&&console.log(S)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{h(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),h({success:!1,output:"",error:v.message})})});if(!p.success)return Q({error:"Failed to capture screenshot",details:p.error},{status:500});const u=p.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return Q({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return Q(m)}catch(t){return console.error("[Capture] Error:",t),Q({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const a0=Object.freeze(Object.defineProperty({__proto__:null,action:o0},Symbol.toStringTag,{value:"Module"}));function i0(e){const t=e||process.cwd();try{return Ae("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 l0(e){const t=e||process.cwd();try{return Ae("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function c0(e){if(l0(e))return!1;Ae("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Ae('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Ae('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function d0(e){Ae("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function u0(e,t){return Ae(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),i0(e)}function p0(e){return/^[0-9a-f]{7,40}$/i.test(e)}function m0(e,t){try{return Ae(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function h0(e,t){try{return{stashed:!Ae(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function f0(e,t){Ae(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function g0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!p0(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!m0(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:o}=h0(s,"codeyam: auto-stash before time travel");o&&console.log("[editor-load-commit] Stashed uncommitted changes");try{f0(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(a){const i=a instanceof Error?a.message:String(a);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(a){console.warn("[editor-load-commit] Dev server restart warning:",a)}return new Response(JSON.stringify({success:!0,stashed:o}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const y0=Object.freeze(Object.defineProperty({__proto__:null,action:g0},Symbol.toStringTag,{value:"Module"}));async function x0(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await ze();const s=await jt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=Me(),a=s.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",a).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await o.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",a).execute(),console.log(`[recapture] Updated defaultWidth for entity ${a} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await wn(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const c=pe();if(!c)throw new Error("Project root not found");const p=F.join(c,".codeyam","config.json"),u=JSON.parse(K.readFileSync(p,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${h}`),{jobId:h}}async function b0(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await ze();const s=await jt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const o=(u=s.scenarios)==null?void 0:u.find(m=>m.id===t);if(!o)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${o.name}`),await wn(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const h=m.scenarios.find(f=>f.name===o.name);h&&(delete h.finishedAt,delete h.startedAt,delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${o.name} for recapture`);const a=pe();if(!a)throw new Error("Project root not found");const i=F.join(a,".codeyam","config.json"),l=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${p}`),{jobId:p}}async function v0({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Tt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("scenarioId");if(!o||!a)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${a}`);const i=await b0(o,a,r);return console.log("[API] Scenario recapture queued",i),Q({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),Q({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const w0=Object.freeze(Object.defineProperty({__proto__:null,action:v0},Symbol.toStringTag,{value:"Module"}));async function Zs(e){try{return await we.stat(e),!0}catch{return!1}}async function ql(){try{const e=pe();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await we.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function N0(){return`/private/tmp/claude-501/-${(pe()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const yr="/tmp/claude-rule-markers",C0=/<system-reminder>[\s\S]*?<\/system-reminder>/g,Ua=2e3;function S0(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 k0=["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 E0(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const o=String(s.input.file_path||"");if(o.includes(".claude/rules/")){const a=o.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${a}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:a,content:String(s.input.content||"")}):t.push({action:"modified",filePath:a,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const o=String(s.input.command||"");if(o.includes("codeyam memory touch")){const a=`touch:${o}`;r.has(a)||(r.add(a),t.push({action:"touched",filePath:o}))}}}return t}function A0(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const o=s.indexOf(`
|
|
257
|
+
###`);return o!==-1&&(s=s.slice(0,o).trim()),s||void 0}function P0(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of k0)if(r.includes(s))return!0}return!1}function _0(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const o=(s.message||{}).model;if(typeof o=="string"&&o)return o}}catch{continue}}}function j0(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const o={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(o.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(o.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(o.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(o.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){o.usage={};for(const a of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[a]=="number"&&(o.usage[a]=s.usage[a])}return Array.isArray(s.errors)&&s.errors.length>0&&(o.errors=s.errors.map(String)),o}catch{continue}}}function M0(e){const t=[],r={};for(const s of e){const o=s.trim();if(!o)continue;let a;try{a=JSON.parse(o)}catch{continue}const i=a.type;if(i==="progress"||i==="system"||i==="result")continue;const c=(a.message||{}).content,p=a.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:p,agent_id:String(a.agentId||a.session_id||"unknown"),slug:String(a.slug||"")});else if(Array.isArray(c)){for(const u of c)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,h=String(m.tool_use_id||"");let f=m.content;const y=!!m.is_error;typeof f=="string"&&(f=f.replace(C0,"").trim()),t.push({type:"tool_result",tool_use_id:h,tool_name:r[h]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:p})}}}else if(i==="assistant"&&Array.isArray(c))for(const u of c){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const h=String(m.text||"").trim();h&&t.push({type:"assistant_text",text:h,timestamp:p})}else if(m.type==="tool_use"){const h=String(m.id||""),f=String(m.name||"unknown"),y=m.input||{};r[h]=f,t.push({type:"tool_call",tool_use_id:h,name:f,input:y,timestamp:p})}}}return t}function T0(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 mn=20;async function Wa(e){const r=(await we.readFile(e.filePath,"utf-8")).split(`
|
|
258
|
+
`),s=M0(r);if(s.length===0)return null;const o=s.find(w=>w.type==="user_prompt"),a=e.stem,i=_0(r);let l=(o==null?void 0:o.slug)||"",c=(o==null?void 0:o.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let p;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const w=e.filePath.replace(/\.log$/,".context");if(await Zs(w))try{p=await we.readFile(w,"utf-8")}catch{}}const u=s.filter(w=>w.type==="tool_call").length,m=s.filter(w=>w.type==="assistant_text").length,h=s.filter(w=>w.type==="tool_result"&&w.is_error&&w.content!=="Sibling tool call errored"),f=h.length,y=h.map(w=>{const S=w.content||"Unknown error";return S.length>150?S.slice(0,150)+"...":S});for(const w of s)w.type==="tool_call"&&w.name&&w.input&&(w.summary=S0(w.name,w.input));for(const w of s)w.type==="tool_result"&&w.content&&w.content.length>Ua&&(w.truncated=!0,w.fullLength=w.content.length,w.content=w.content.slice(0,Ua));const g=E0(s),x=P0(s),v=A0(p),b=j0(r);return{id:a,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:m,errors:f,errorMessages:y},entries:s,context:p,conversationSnippet:v,ruleChanges:g,hasConfusion:x,sessionResult:b}}async function $0(){const e=N0(),t=yr,r=[];if(await Zs(e)){const i=await we.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=ee.join(e,l),p=await we.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:p.mtimeMs})}}const s=new Set,o=await ql(),a=[];o&&a.push(ee.join(t,o)),a.push(t);for(const i of a){if(!await Zs(i))continue;const l=await we.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const p=ee.join(i,c),u=await we.stat(p);r.push({filePath:p,stem:c.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function R0({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",o=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),a=await $0();if(!s){const u=a.length,m=(o-1)*mn,h=a.slice(m,m+mn),f=[];for(const y of h){const g=await Wa(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:o,pageSize:mn})}const i=[];for(const u of a){const m=await Wa(u);if(!m)continue;(m.id.toLowerCase().includes(s)||m.slug.toLowerCase().includes(s)||m.entries.some(f=>T0(f,s)))&&i.push(m)}const l=i.length,c=(o-1)*mn,p=i.slice(c,c+mn);return Response.json({agents:p,total:l,page:o,pageSize:mn})}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 I0=Object.freeze(Object.defineProperty({__proto__:null,loader:R0},Symbol.toStringTag,{value:"Module"})),Kl="__codeyam_editor_dev_server__",Ja=30;function Ro(){return globalThis[Kl]??null}function Ql(e){globalThis[Kl]=e}function Ps(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{fe.existsSync(s)&&(fe.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(o){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,o)}if(t)try{const s=Ae(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(Ae(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function D0({request:e}){const t=Ro();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Sl(),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 O0({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"?Xs():r==="stop"?Ha():r==="restart"?(Ha(),await new Promise(s=>setTimeout(s,1e3)),Xs()):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 L0(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const o=ee.dirname(t);if(ee.basename(o)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:o;break}t=o}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(fe.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Xs(e=!1){var k,N;const t=Ro();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=pe()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:o,devServerPort:a}=bl(s),i=uh(r,a);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:c,env:p}=i;Ps(r,3e3),Ps(r,3001),Ps(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const u=L0(),m=u?`--import ${u}`:"",{NODE_OPTIONS:h,PORT:f,CODEYAM_PORT:y,...g}=process.env,x={};try{const C=ee.join(r,".codeyam","config.json"),A=JSON.parse(fe.readFileSync(C,"utf-8"));for(const T of A.environmentVariables||[])T.key&&T.value!==void 0&&(x[T.key]=T.value)}catch{}const v=At(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...g,...x,FORCE_COLOR:"1",BROWSER:"none",...m?{NODE_OPTIONS:m}:{},CODEYAM_PROXY_URL:`http://localhost:${o}`,...p},detached:!0});v.unref();const b=e?((t==null?void 0:t.retryCount)??0)+1:0,w={process:v,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:v.pid||0,startedAt:Date.now(),retryCount:b};Ql(w);const S=(C,A)=>{const T=C.toString();if(A){const P=T.split(`
|
|
259
|
+
`).filter(_=>_.trim());w.stderrBuffer.push(...P),w.stderrBuffer.length>Ja&&(w.stderrBuffer=w.stderrBuffer.slice(-Ja))}if(w.status==="starting"){const P=mh(T);P&&(w.url=P,w.status="running",console.log(`[editor-dev-server] URL detected: ${w.url}`),Ws({port:o,targetUrl:w.url}).then(()=>Da()))}};(k=v.stdout)==null||k.on("data",C=>S(C,!1)),(N=v.stderr)==null||N.on("data",C=>S(C,!0));const E=parseInt(p.PORT||"0",10);return E>0&&(async()=>{if(await new Promise(A=>setTimeout(A,1e4)),w.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${E}...`);const C=await fh(E,{intervalMs:2e3,maxAttempts:15});C&&w.status==="starting"&&(w.url=C,w.status="running",console.log(`[editor-dev-server] URL detected via polling: ${w.url}`),Ws({port:o,targetUrl:w.url}).then(()=>Da()))})(),v.on("exit",C=>{console.log(`[editor-dev-server] Process exited with code ${C}`);const A=Date.now()-w.startedAt,T=gh({exitCode:C??null,uptime:A,retryCount:w.retryCount});T.action==="retry"?(console.log(`[editor-dev-server] Quick failure (${A}ms), auto-retrying...`),w.status="stopped",Xs(!0)):T.action==="error"?(w.status="error",w.errorMessage=w.stderrBuffer.length>0?w.stderrBuffer.join(`
|
|
260
|
+
`):`Dev server exited with code ${C}`,console.error(`[editor-dev-server] Server failed: ${w.errorMessage}`)):w.status="stopped"}),v.on("error",C=>{console.error("[editor-dev-server] Process error:",C),w.status="error",w.errorMessage=C.message}),new Response(JSON.stringify({status:"starting",pid:v.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function Ha(){const e=Ro();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});El();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",Ql(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const F0=Object.freeze(Object.defineProperty({__proto__:null,action:O0,loader:D0},Symbol.toStringTag,{value:"Module"}));async function z0({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=Gr(r);try{return await On(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(o){console.error("[api.logs] Error clearing log file:",o);const a=o instanceof Error?o.message:String(o);return new Response(`Error clearing log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function B0({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Gr(t);try{if(!Ot(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 Ds(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Y0=Object.freeze(Object.defineProperty({__proto__:null,action:z0,loader:B0},Symbol.toStringTag,{value:"Module"}));function U0({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=pe()||process.cwd(),o=F.resolve(s,r);if(!o.startsWith(s+F.sep)&&o!==s)return Response.json({error:"Path outside project root"},{status:403});const a=Dl(r,s);return Response.json(a)}const W0=Object.freeze(Object.defineProperty({__proto__:null,loader:U0},Symbol.toStringTag,{value:"Module"}));async function J0(){const e=await Te();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await $e(e),r=Me(),s=process.env.CODEYAM_PORT||"3111",o=pe()||process.cwd(),a=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=kt(a,p=>`${p.name}::${p.url||"/"}`);let l={};try{const p=i.map(m=>({componentName:m.component_name||null,componentPath:m.component_path||null,url:m.url??null}));l=(await rs({projectRoot:o,scenarioInputs:p})).entityChangeStatus}catch{}const c=i.map(p=>{let u=null;p.component_name?u=p.component_name:u=nt(p.url??null);const m=u?l[u]:void 0;return{id:p.id,name:p.name,componentName:p.component_name||null,type:p.type||null,changeStatus:(m==null?void 0:m.status)||null,link:`http://localhost:${s}/editor?scenario=${p.id}&ref=link`}});return Response.json({scenarios:c})}const H0=Object.freeze(Object.defineProperty({__proto__:null,loader:J0},Symbol.toStringTag,{value:"Module"}));async function V0(e,t){var a,i,l,c,p,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await ze();const r=await jt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(a=r.scenarios)==null?void 0:a.find(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 o={returnValue:{status:"success",data:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(p=s.metadata)==null?void 0:p.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),o}async function G0({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const o=await V0(r,s);return console.log("[API] Function execution completed successfully"),Q({success:!0,result:o})}catch(t){return console.log("[API] Error during function execution:",t),Q({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const q0=Object.freeze(Object.defineProperty({__proto__:null,action:G0},Symbol.toStringTag,{value:"Module"}));function K0({request:e}){return Q({status:"ok"})}async function Q0({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Tt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("action"),a=s.get("analysisId"),i=s.get("scenarioId");if(!o||!a)return Q({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return Q({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Te();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return Q({error:"Project not initialized"},{status:500});if(o==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:a,scenarioId:i,projectSlug:l});return Q({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:a,projectSlug:l});return Q({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}catch(s){console.error("[Interactive Mode API] Error:",s);const o=s instanceof Error?s.message:String(s),a=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",a),Q({error:"Failed to control interactive mode",details:o},{status:500})}}const Z0=Object.freeze(Object.defineProperty({__proto__:null,action:Q0,loader:K0},Symbol.toStringTag,{value:"Module"}));async function X0({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const o=pe();if(o)for(const a of s){const i=ee.join(o,".codeyam","captures","screenshots",a);try{await we.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await Tu({ids:[r]});try{const o=pe()||process.cwd();_h(o,r)}catch{}return console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const ey=Object.freeze(Object.defineProperty({__proto__:null,action:X0},Symbol.toStringTag,{value:"Module"}));class ty extends Fr{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 eo="__codeyam_dev_mode_event_emitter__";if(!globalThis[eo]){const e=new ty;e.setMaxListeners(20),globalThis[eo]=e}const Va=globalThis[eo];function ny({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
261
|
+
|
|
262
|
+
`));let o=!1;const a=()=>{if(!o){o=!0,Va.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
|
|
263
|
+
|
|
264
|
+
`))}catch{a()}};Va.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
265
|
+
|
|
266
|
+
`))}catch{a()}},3e4);e.signal.addEventListener("abort",a)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const ry=Object.freeze(Object.defineProperty({__proto__:null,loader:ny},Symbol.toStringTag,{value:"Module"})),Jn="/tmp/codeyam",to=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Zl=500,sy=Zl*1024*1024;function tn(e,t){try{return Ae(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function xr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Xl(e){return tn("config user.email",e)}function oy(e){const t=F.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function ay(e,t=20){const r=F.join(Jn,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
|
|
267
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function iy(e){try{const t=await fetch(`${to}/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 ly(e,t){try{Ae(`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 cy(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:o,screenshot:a,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),p=F.join(Jn,`delta-staging-${c}`),u=F.join(p,"delta");K.mkdirSync(u,{recursive:!0});try{const m=tn("diff --binary HEAD",t)||"";K.writeFileSync(F.join(u,"tracked.patch"),m?m+`
|
|
268
|
+
`:"");const h=tn("ls-files --others --exclude-standard",t);if(h){const x=F.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const v of h.split(`
|
|
269
|
+
`).filter(Boolean)){const b=F.join(t,v),w=F.join(x,v);if(K.existsSync(b)){const S=F.dirname(w);K.mkdirSync(S,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,w)}}}const f=F.join(t,".codeyam");if(K.existsSync(f)){const x=F.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(F.join(u,"meta.json"),JSON.stringify(o,null,2));const y=F.join(Jn,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,F.join(u,"codeyam-log.txt")):K.writeFileSync(F.join(u,"codeyam-log.txt"),`# Log file not found
|
|
270
|
+
`);const g=F.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,F.join(u,"debug-report.md")),l("Debug report included")),a&&a.length>0&&(K.writeFileSync(F.join(u,"screenshot.jpg"),a),l(`Screenshot included (${xr(a.length)})`));try{Ae(`tar -czf "${s}" -C "${p}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(p,{recursive:!0,force:!0})}}async function dy(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:o,onProgress:a}=e,i=a||(()=>{});i("Gathering metadata...");const l=tn("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const c=tn("rev-parse --abbrev-ref HEAD",t)||"unknown",p=tn("status --porcelain",t),u=tn("remote get-url origin",t),m=p!==null&&p.length>0,h=ul(r),f=oy(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:c,isDirty:m,remoteUrl:u},versions:{cli:h.cliVersion,webserver:h.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=F.join(Jn,`base-${l}-${x}.tar.gz`),b=F.join(Jn,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const w=await iy(l);let S=null;w?i("Server already has base, skipping..."):(i("Generating base archive..."),ly(t,v),S=K.statSync(v).size,i(`Base archive: ${xr(S)}`)),i("Generating delta archive..."),cy({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:o,onProgress:a});const k=K.statSync(b).size;i(`Delta archive: ${xr(k)}`);const N=(S||0)+k;if(N>sy)throw K.existsSync(v)&&K.unlinkSync(v),K.unlinkSync(b),new Error(`Bundle too large: ${xr(N)} (max: ${Zl} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:w?null:v,deltaPath:b,metadata:g,baseSha:l,baseSize:S,deltaSize:k}}async function uy(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:o,baseSha:a,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),p=K.statSync(r),u=t?K.statSync(t):null,m=p.size+((u==null?void 0:u.size)||0);c("Requesting upload URLs...");const h=await fetch(`${to}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:m,baseSha:a,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:o.timestamp,git:o.git,versions:o.versions,system:o.system,feedback:o.feedback}})});if(!h.ok){const w=await h.json();throw new Error(w.error||`Server returned ${h.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await h.json(),x=[];if(t&&g){c("Uploading base...");const w=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(S=>{if(!S.ok)throw new Error(`Base upload failed: ${S.status}`)}))}c("Uploading delta...");const v=K.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),c("Confirming upload...");const b=await fetch(`${to}/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&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function py({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),o=t.get("email"),a=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),c=t.get("analysisId"),p=t.get("currentUrl"),u=t.get("entityName"),m=t.get("entityType"),h=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(h?g=`Issue on ${u} scenario "${h}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const N=await y.arrayBuffer();x=Buffer.from(N),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=pe();if(!v)return Q({error:"Project root not found"},{status:500});const b=await Te();if(!b)return Q({error:"Project slug not found"},{status:500});const w={issueType:r||"other",description:g,email:o||void 0,source:a||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:p||void 0,recentActivity:ay(b,20),entityName:u||void 0,entityType:m||void 0,scenarioName:h||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${w.source}, issue: ${w.issueType}`);const S=await dy({projectRoot:v,projectSlug:b,feedback:w,screenshot:x,onProgress:N=>{console.log(`[Bundle] ${N}`)}}),E=(S.baseSize||0)+S.deltaSize;console.log(`[Bundle] Archives created: delta=${S.deltaSize} bytes${S.basePath?`, base=${S.baseSize} bytes`:" (base reused)"}`);const k=await uy({basePath:S.basePath,deltaPath:S.deltaPath,projectSlug:b,metadata:S.metadata,baseSha:S.baseSha,deltaSize:S.deltaSize,onProgress:N=>{console.log(`[Bundle] ${N}`)}});return console.log(`[Bundle] Upload complete: ${k.bundleId}`),Q({success:!0,reportId:k.bundleId,size:E})}catch(t){return console.error("[Bundle] Error:",t),Q({error:t.message||"Failed to generate bundle"},{status:500})}}function my(){const e=pe(),t=e?Xl(e):null;return Q({defaultEmail:t})}const hy=Object.freeze(Object.defineProperty({__proto__:null,action:py,loader:my},Symbol.toStringTag,{value:"Module"}));async function fy({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),o=F.join(s,".codeyam","journal","index.json");let a={entries:[]};try{const l=await ve.readFile(o,"utf8");a=JSON.parse(l)}catch{}let i=a.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const gy=Object.freeze(Object.defineProperty({__proto__:null,loader:fy},Symbol.toStringTag,{value:"Module"}));function ec(e){if(!K.existsSync(e))return He.Unknown;try{const t=JSON.parse(K.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?He.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?He.Remix:r["react-scripts"]?He.CRA:r.expo?He.Expo:r.vite?He.Vite:He.Unknown}catch{return He.Unknown}}function yy(e,t){let r=e;const s=F.resolve(t);for(;;){const o=F.resolve(r);if(K.existsSync(F.join(o,"pnpm-lock.yaml")))return"pnpm";if(K.existsSync(F.join(o,"yarn.lock")))return"yarn";if(K.existsSync(F.join(o,"package-lock.json")))return"npm";if(o===s)break;const a=F.dirname(o);if(a===o)break;r=a}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function xy(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function by(e){const t=F.join(e,"package.json");if(!K.existsSync(t))return{isWebApp:!1};if(ec(t)===He.Unknown)return{isWebApp:!1};try{const o=JSON.parse(K.readFileSync(t,"utf8")).scripts||{},a=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(o).filter(c=>["dev","start","serve","build"].some(p=>c.includes(p))).filter(c=>a.some(p=>o[c].includes(p)));if(l.length===0)return{isWebApp:!1};for(const c of l){const p=o[c],u=xy(p);if(u){const m=F.join(e,u);if(K.existsSync(m)&&K.statSync(m).isDirectory())return{isWebApp:!0,actualPath:m}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function tc(e,t=e,r=0,s=3){if(r>s)return[];const o=[],a=by(t);if(a.isWebApp){const l=a.actualPath||t,c=F.relative(e,l);return o.push(c||"."),o}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=K.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const p=F.join(t,c.name);o.push(...tc(e,p,r+1,s))}}catch{}return o}function vy(e){const t=tc(e);return t.length===0?[]:t.map(s=>{const o=F.join(e,s),a=F.join(o,"package.json"),i=ec(a),l=yy(o,e);let c;if(i===He.Remix||i===He.Next){const m=F.join(o,"app");K.existsSync(m)&&K.statSync(m).isDirectory()&&(c="app")}const p=wy(s,e),u=p?{command:"sh",args:["-c",`${l} run ${p} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:u}})}function wy(e,t){const r=F.join(t,e),s=F.join(r,"package.json");if(!K.existsSync(s))return null;try{const a=JSON.parse(K.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(a[l])return l;return null}catch{return null}}function Ny(e,t){const r=new Set(e.map(o=>o.path)),s=[...e];for(const o of t)r.has(o.path)||s.push(o);return s}async function Cy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=pe()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=vy(t)}catch{}if(fe.existsSync(r)){const i=JSON.parse(fe.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=Ny(s,l),s=i.webapps,fe.writeFileSync(r,JSON.stringify(i,null,2))}const o=await Te();if(o)try{await xn({projectSlug:o,metadataUpdate:{webapps:s}})}catch{}let a=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",c=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(c.status==="stopped"||c.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),a=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:a,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Sy=Object.freeze(Object.defineProperty({__proto__:null,action:Cy},Symbol.toStringTag,{value:"Module"}));function rn(){const e=process.memoryUsage(),t=Id.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(Os.totalmem()/1024/1024),freeMemory:Math.round(Os.freemem()/1024/1024)}}}function ky(){const e=rn();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 Ey(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=rn();global.gc();const t=rn(),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 Ay(){const e=rn(),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 Py({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=Ey(),o=rn();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:o})}case"detailed":{const s=ky();return Response.json({success:!0,stats:s})}case"leaks":{const s=Ay(),o=rn();return Response.json({success:!0,leakCheck:s,stats:o})}default:{const s=rn();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 _y=Object.freeze(Object.defineProperty({__proto__:null,loader:Py},Symbol.toStringTag,{value:"Module"})),dr=co(lo);async function jy({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const o=await Promise.all(s.map(async a=>{const i=My(a),l=i?await Ty(a):null;return{pid:a,isRunning:i,processName:l}}));return Response.json({processes:o})}function My(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ty(e){if(process.platform==="win32")try{const{stdout:r}=await dr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const o=s[1];if(o.toLowerCase()==="node.exe")try{const{stdout:a}=await dr(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=a.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return o}catch{return null}try{const{stdout:r}=await dr(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await dr(`ps -p ${e} -o args=`),o=s.trim(),a=o.match(/codeyam-(\w+)/);return a?`codeyam-${a[1]}`:o.split(" ")[0]||null}catch{return null}}}const $y=Object.freeze(Object.defineProperty({__proto__:null,loader:jy},Symbol.toStringTag,{value:"Module"})),Ry=Lr(import.meta.url),Iy=F.dirname(Ry);function Dy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=ml(),r=pe()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,o=F.join(Iy,"..","..","..","..","webserver","bootstrap.js"),a=F.join(r,".codeyam","logs");K.existsSync(a)||K.mkdirSync(a,{recursive:!0});const i=K.openSync(F.join(a,"background-server.log"),"a"),l=K.openSync(F.join(a,"background-server-error.log"),"a"),c=new Date().toISOString();K.appendFileSync(F.join(a,"background-server.log"),`
|
|
272
|
+
[${c}] Server restart requested via dashboard
|
|
273
|
+
`),zp();const p=At("node",[o],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});p.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${p.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 Oy=Object.freeze(Object.defineProperty({__proto__:null,action:Dy},Symbol.toStringTag,{value:"Module"}));async function Ly({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,c)=>{var m,h,f,y,g;const p=(h=(m=l.metadata)==null?void 0:m.data)==null?void 0:h.argumentsData,u=Array.isArray(p)&&p.length>0?JSON.stringify(p[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(p)?p.length:"not-array",argumentsDataPreview:u})});const o=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),a=await qu(o);if(!a||a.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${a.length} scenarios to database`),a.forEach((l,c)=>{var u,m;const p=(m=(u=l.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(p)?p.length:"not-array"})});const i={...r,scenarios:a};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const Fy=Object.freeze(Object.defineProperty({__proto__:null,action:Ly},Symbol.toStringTag,{value:"Module"})),zy=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function By({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",o=new URLSearchParams;r&&o.set("search",r),s!=="1"&&o.set("page",s);const a=o.toString(),i=new URL(`/api/agent-transcripts${a?`?${a}`:""}`,e.url),c=await(await fetch(i.toString())).json();if(c.error)return Q({agents:[],error:c.error,search:r,page:1,totalPages:1});const p=c.total??(c.agents||[]).length,u=c.pageSize??20;return Q({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(p/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),Q({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function Yy(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 Uy(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 Wy(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function br({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 Jy({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),d("div",{children:[d("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function Hy({content:e,truncated:t,fullLength:r}){const[s,o]=M(!1);return d("div",{children:[d("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>o(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Vy({entry:e,pairedResult:t}){const[r,s]=M(!1),o=Yy(e.timestamp||"");return e.type==="user_prompt"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(br,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:o})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(br,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:o})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?d("div",{className:"my-2",children:[d("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(lt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Yt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(br,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:o})]}),r&&d("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Jy,{input:e.input||{}}),t&&d("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[d("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Hy,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Gy({context:e}){const[t,r]=M(!1);return d("div",{className:"my-2",children:[d("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(lt,{className:"w-3 h-3 text-gray-400"}):n(Yt,{className:"w-3 h-3 text-gray-400"}),n(br,{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 qy({snippet:e}){const[t,r]=M(!1),s=e.split(`
|
|
274
|
+
`).filter(l=>l.trim()),o=s.slice(0,4),a=s.length>4,i=t?s:o;return d("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n(td,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,c)=>{const p=l.match(/^\[(\w+)\]:\s*(.*)/);if(!p)return null;const[,u,m]=p,h=u==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${h?"text-blue-700":"text-gray-500"}`,children:[h?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:m.length>200?m.slice(0,200)+"...":m})]},c)})}),a&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function Ky({change:e}){const[t,r]=M(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return d("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:d("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(lt,{className:"w-3 h-3 inline flex-shrink-0"}):n(Yt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&d("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&d("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&d("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function Qy({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),o=r.some(i=>i.action==="modified");return d("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":o?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),d("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(Ky,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Zy({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",o=t?"text-red-700":"text-green-700",a=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",a]}),d("div",{className:`text-xs ${o} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((c,p)=>n("div",{className:"text-red-700 break-words",children:c},p))})]})]})}function Xy({agent:e,defaultOpen:t,isAdmin:r}){var E,k,N;const[s,o]=M(t),[a,i]=M(!1),[l,c]=M(null),[p,u]=M(!1),m=ne(()=>{const C={};for(const A of e.entries)A.type==="tool_result"&&A.tool_use_id&&(C[A.tool_use_id]=A);return C},[e.entries]),h=ne(()=>{const C=new Set;for(const A of e.entries)A.type==="tool_call"&&A.tool_use_id&&m[A.tool_use_id]&&C.add(A.tool_use_id);return C},[e.entries,m]),f=C=>{C.stopPropagation(),i(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(A=>A.json()).then(A=>{A.success?c(`Saved to ${A.fixturePath}`):c(`Error: ${A.error}`)}).catch(A=>{c(`Error: ${A instanceof Error?A.message:String(A)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(C=>C.action!=="touched"),g=y.filter(C=>C.action==="created"),x=y.filter(C=>C.action==="modified"),v=(e.ruleChanges||[]).filter(C=>C.action==="touched"),b=y.length>0,w=v.length>0,S=b||w;return d("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[d("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(lt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Yt,{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:Wy(e.model)}),g.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(wr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(wr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&w&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(vr,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),d("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((E=e.sessionResult)==null?void 0:E.duration_ms)!=null&&d(ue,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((k=e.sessionResult)==null?void 0:k.total_cost_usd)!=null&&d(ue,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),d("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[Uy(e.timestamp),r&&b&&d("button",{onClick:f,disabled:a,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(ed,{className:"w-3 h-3"}),a?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&d("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&d("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:C=>{C.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:p?n(ft,{className:"w-3.5 h-3.5 text-green-500"}):n(St,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(Zy,{result:e.sessionResult}),e.stats.errors>0&&((N=e.stats.errorMessages)==null?void 0:N.length)>0&&d("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[d("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((C,A)=>n("li",{className:"break-words",children:C},A))})]}),e.conversationSnippet&&n(qy,{snippet:e.conversationSnippet}),S&&n(Qy,{changes:e.ruleChanges}),e.context&&n(Gy,{context:e.context}),e.entries.map((C,A)=>{if(C.type==="tool_result"&&C.tool_use_id&&h.has(C.tool_use_id))return null;const T=C.type==="tool_call"&&C.tool_use_id?m[C.tool_use_id]:void 0;return n(Vy,{entry:C,pairedResult:T},`${e.id}-${A}`)})]})]})}function _s(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 ex=We(function(){const{agents:t,error:r,search:s,page:o,totalPages:a}=Ve(),i=Et(),l=Tc("root"),c=(l==null?void 0:l.isAdmin)??!1,[p,u]=M(s),[m,h]=M(!1),[f,y]=M(0);gt({source:"agent-transcripts-page"});const g=v=>{v.preventDefault(),window.location.href=_s(1,p)},x=()=>{h(!m),y(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[d("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Zc,{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"})]}),d("div",{className:"flex items-center gap-4 mb-6",children:[d("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Vn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:p,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"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",o," of ",a,s&&d("span",{children:[" ","matching “",s,"”",n(de,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(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(Xy,{agent:v,defaultOpen:m,isAdmin:c},v.id))},f),a>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:o>1?_s(o-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${o>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(Xc,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[o," / ",a]}),d("a",{href:o<a?_s(o+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${o<a?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(Yt,{className:"w-4 h-4"})]})]})]})})}),tx=Object.freeze(Object.defineProperty({__proto__:null,default:ex,loader:By,meta:zy},Symbol.toStringTag,{value:"Module"}));async function nx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const o=c0(s);o&&console.log("[editor-commit] Initialized new git repository"),d0(s),console.log("[editor-commit] Staged all changes");const a=u0(s,r);console.log(`[editor-commit] Created commit: ${a}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>Mh);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:a,initialized:o}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const rx=Object.freeze(Object.defineProperty({__proto__:null,action:nx},Symbol.toStringTag,{value:"Module"})),sx=["JSX","React","Element","ReactNode"];function ox(e){return e.returnType?sx.some(t=>e.returnType.includes(t)):!1}function ax(e){const t=[],r=[];for(const s of e)ox(s)?t.push(s):r.push(s);return{components:t,functions:r}}function ix({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:o,clientErrors:a}){const i=e.map(g=>{const x=r[g.name]||0,v=a==null?void 0:a[g.name],b=x>0&&v&&v.length>0;let w;return x===0?w="missing":b?w="has_errors":w="ok",{name:g.name,filePath:g.filePath,scenarioCount:x,status:w,...b?{clientErrors:v}:{}}}),l=t.map(g=>{if(!(g.testFile?s[g.testFile]??!1:!1))return{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!1,status:"missing"};const v=g.testFile&&o?o[g.testFile]:void 0;if(!v)return{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!0,status:"ok"};let b;return v.passing?v.hasEntityNameDescribe?b="ok":b="name_mismatch":b="failing",{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!0,testsPassing:v.passing,testsVisibleInUi:v.hasEntityNameDescribe,status:b}}),c=i.filter(g=>g.status==="ok").length,p=i.filter(g=>g.status==="has_errors").length,u=i.filter(g=>g.status==="missing").length,m=l.filter(g=>g.status==="ok").length,h=l.filter(g=>g.status==="failing").length,f=l.filter(g=>g.status==="name_mismatch").length,y=l.filter(g=>g.status==="missing").length;return{components:i,functions:l,summary:{totalComponents:i.length,componentsOk:c,componentsMissing:u,componentsWithErrors:p,totalFunctions:l.length,functionsOk:m,functionsMissing:y,functionsFailing:h,functionsNameMismatch:f,allPassing:u===0&&p===0&&h===0&&f===0&&y===0}}}function lx(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function cx(){const e=pe()||process.cwd(),t=F.join(e,".codeyam","glossary.json");let r;try{const g=K.readFileSync(t,"utf8");r=JSON.parse(g),Array.isArray(r)||(r=[])}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,componentsWithErrors:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}})}if(r.length===0)return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,componentsWithErrors:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}});const s=F.join(e,".codeyam","editor-step.json");let o=null;try{const g=K.readFileSync(s,"utf8");o=JSON.parse(g).featureStartedAt||null}catch{}let a;const i=await Te();if(i)try{const{project:g}=await $e(i),v=await Me().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",g.id).orderBy("created_at","asc").execute(),w=kt(v,E=>`${E.name}::${E.url||"/"}`).map(E=>({componentName:E.component_name||null,componentPath:E.component_path||null,url:E.url??null})),S=await rs({projectRoot:e,scenarioInputs:w});Object.keys(S.entityChangeStatus).length>0&&(a=S.entityChangeStatus)}catch{}const l=lx(r,a),{components:c,functions:p}=ax(l),u={};if(i)try{const{project:g}=await $e(i),x=Me();let v=x.selectFrom("editor_scenarios").select(["component_name"]).select(x.fn.count("id").as("count")).where("project_id","=",g.id).where("component_name","is not",null).groupBy("component_name");if(o){const w=o.replace("T"," ").replace(/\.\d{3}Z$/,"");v=v.where("created_at",">=",w)}const b=await v.execute();for(const w of b)w.component_name&&(u[w.component_name]=Number(w.count))}catch{}const m={};try{const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=await jl(g);for(const[,v]of Object.entries(x)){if(v.errors.length===0)continue;const b=v.scenarioName,w=b.indexOf(" - "),S=w>=0?b.slice(0,w):b;S&&(m[S]||(m[S]=[]),m[S].push(...v.errors))}}catch{}const h={};for(const g of p)g.testFile&&(h[g.testFile]=K.existsSync(F.join(e,g.testFile)));const f={};for(const g of p)if(!(!g.testFile||!h[g.testFile]))try{const x=await Vl(e,g.testFile),v=x.status==="passed",b=x.testCases.some(w=>w.fullName.startsWith(g.name));f[g.testFile]={passing:v,hasEntityNameDescribe:b}}catch{f[g.testFile]={passing:!1,hasEntityNameDescribe:!1}}const y=ix({components:c,functions:p,scenarioCounts:u,testFileExistence:h,testResults:f,clientErrors:m});return Response.json(y)}const dx=Object.freeze(Object.defineProperty({__proto__:null,loader:cx},Symbol.toStringTag,{value:"Module"}));async function ux({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:o}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Ga(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,l=500,c=Date.now();let p=!0;for(;p&&Date.now()-c<i;)await new Promise(u=>setTimeout(u,l)),p=Ga(r);if(p){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(o)try{await Lt({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-c})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Ga(e){try{return process.kill(e,0),!0}catch{return!1}}const px=Object.freeze(Object.defineProperty({__proto__:null,action:ux},Symbol.toStringTag,{value:"Module"})),mx=Lr(import.meta.url),hx=ee.dirname(mx),fx=ee.resolve(hx,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function gx(e){const t=[],r=new Set;for(const s of e.split(`
|
|
275
|
+
`)){const o=s.trim();if(!o)continue;let a;try{a=JSON.parse(o)}catch{continue}if(a.type!=="assistant")continue;const i=a.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type!=="tool_use")continue;const p=String(c.name||""),u=c.input||{};if(p==="Write"||p==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const h=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${p}:${h}`;r.has(f)||(r.add(f),t.push({action:p==="Write"?"created":"modified",filePath:h}))}}else if(p==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const h=`touch:${m}`;r.has(h)||(r.add(h),t.push({action:"touched",filePath:m}))}}}}return t}async function yx({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 ql(),o=s?ee.join(yr,s):null;let a=o?ee.join(o,`${r}.log`):"";if((!a||!Ot(a))&&(a=ee.join(yr,`${r}.log`)),!Ot(a))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await Ds(a,"utf-8");let l=o?ee.join(o,`${r}.context`):"";(!l||!Ot(l))&&(l=ee.join(yr,`${r}.context`));let c=null;if(Ot(l))try{c=await Ds(l,"utf-8")}catch{}const p=gx(i),m=c?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>c.toLowerCase().includes(x)):!1,h=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+h,y=ee.join(fx,f);await Cd(y,{recursive:!0}),await On(ee.join(y,"agent-log.jsonl"),i),c&&await On(ee.join(y,"context.md"),c),await On(ee.join(y,"rule-changes.json"),JSON.stringify(p,null,2)),await On(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:m,ruleChangeCount:p.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const xx=Object.freeze(Object.defineProperty({__proto__:null,action:yx},Symbol.toStringTag,{value:"Module"}));async function bx({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=pe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await we.access(s);const o=await we.readFile(s),a=ee.extname(s).toLowerCase(),i=a===".png"?"image/png":a===".jpg"||a===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const vx=Object.freeze(Object.defineProperty({__proto__:null,loader:bx},Symbol.toStringTag,{value:"Module"})),qa={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 Io({type:e,className:t=""}){const r=qa[e]||qa.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 wx={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 ur({variant:e,pid:t,label:r,className:s=""}){const o=wx[e],a=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:o.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:o.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:a})})}let Ka=!1;function Nx(){if(Ka)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),Ka=!0}function Do({size:e="medium",className:t=""}){typeof document<"u"&&Nx();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:o,gap:a}=r[e];return d("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${a}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${o}px`,height:`${o}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Cx=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function Sx({request:e,context:t,params:r}){var B,D,O,j,q,V,U,Z;let s=t.analysisQueue;s||(s=await Tt());const o=new URL(e.url),a=parseInt(o.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return Q({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:a,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const c=s.getState(),p=await Te();let u=null;if(p&&((B=c==null?void 0:c.currentlyExecuting)!=null&&B.commitSha)){const{project:z,branch:L}=await $e(p),J=await Ar({projectId:z.id,branchId:L.id,shas:[c.currentlyExecuting.commitSha]});u=J&&J.length>0?J[0]:null}else u=await Nn();const m=async z=>{const L=await an(z);if(!L)return null;const{getAnalysesForEntity:J}=await Promise.resolve().then(()=>pp),G=await J(z,!1);return{...L,analyses:G||[]}},h=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async z=>{const L=[];if(z.entityShas&&z.entityShas.length>0){const J=z.entityShas.map(X=>m(X)),G=await Promise.all(J);L.push(...G.filter(X=>X!==null))}return{...z,entities:L}}));let f=null;if(c!=null&&c.currentlyExecuting){const z=c.currentlyExecuting,L=[];if(z.entityShas&&z.entityShas.length>0){const J=z.entityShas.map(X=>m(X)),G=await Promise.all(J);L.push(...G.filter(X=>X!==null))}f={...z,entities:L}}const y=f?h.filter(z=>z.id!==f.id):h,g=((O=(D=u==null?void 0:u.metadata)==null?void 0:D.currentRun)==null?void 0:O.currentEntityShas)||[],v=(await Promise.all(g.map(z=>m(z)))).filter(z=>z!==null),b=[];if(p)try{const{project:z,branch:L}=await $e(p),J=await Ar({projectId:z.id,branchId:L.id,limit:100});for(const G of J){const X=((j=G.metadata)==null?void 0:j.historicalRuns)||[];b.push(...X)}}catch(z){console.error("[activity.tsx] Failed to load historical runs from commits:",z)}const w=[...b].sort((z,L)=>{const J=z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"";return(L.lastCaptureAt||L.analysisCompletedAt||L.archivedAt||L.createdAt||"").localeCompare(J)}),S=(a-1)*i,E=S+i,k=w.slice(S,E),N=Math.ceil(w.length/i),C=await Promise.all(k.map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{...z,entities:[]};const J=await Promise.all(L.map(G=>m(G)));return{...z,entities:J.filter(G=>G!==null)}})),A=!!f,T=y.length,P=w.filter(z=>{const L=!!z.failedAt,J=z.readyToBeCaptured,G=z.capturesCompleted??0,X=J===void 0?!0:J===0||G>=J;return!L&&!!z.analysisCompletedAt&&X}),_=new Set(((q=f==null?void 0:f.entities)==null?void 0:q.map(z=>z.sha))||[]),$=P.filter(z=>!(z.currentEntityShas||[]).some(J=>_.has(J))),R=(await Promise.all($.slice(0,3).map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{run:z,entities:[]};const J=await Promise.all(L.map(G=>m(G)));return{run:z,entities:J.filter(G=>G!==null)}}))).flatMap(({run:z,entities:L})=>L.map(J=>({...J,runId:z.id,completedAt:z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt})));let Y=[],H=null,W=null;if((U=(V=u==null?void 0:u.metadata)==null?void 0:V.currentRun)!=null&&U.analysisCompletedAt&&v.length>0){const z=v[0].sha;H=v[0];const L=await Wr(z);L&&L.length>0&&L[0].scenarios&&(Y=L[0].scenarios,W=L[0].status)}return Q({state:{...c,jobs:y,currentlyExecuting:f},currentRun:(Z=u==null?void 0:u.metadata)==null?void 0:Z.currentRun,historicalRuns:C,totalHistoricalRuns:w.length,currentPage:a,totalPages:N,projectSlug:p,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:l,hasCurrentActivity:A,queuedCount:T,recentCompletedEntities:R,hasMoreCompletedRuns:$.length>3,currentEntityScenarios:Y,currentEntityForScenarios:H,currentAnalysisStatus:W})}function kx({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const o=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:o.map(a=>{const i=e===a.id;return n(de,{to:a.id==="current"?"/activity":`/activity/${a.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:d("span",{className:"flex items-center gap-2",children:[a.label,a.count!==null&&a.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a.count}),a.count===null&&a.hasContent&&n("span",{className:`
|
|
284
|
+
inline-block w-2 h-2 rounded-full
|
|
285
|
+
${i?"":"bg-gray-400"}
|
|
286
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},a.id)})})})}function Ex({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:o,onShowLogs:a,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:p,currentAnalysisStatus:u}){var I,R,Y,H;const[m,h]=M({}),[f,y]=M({isKilling:!1,current:0,total:0}),g=ht(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),w=b&&!!(t!=null&&t.capturePid),S=!b,E=x,k=c||[],{lastLine:N}=Pt(s,E);te(()=>{if(!t)return;const W=[t.analyzerPid,t.capturePid].filter(j=>!!j);if(W.length===0)return;let B=!0;const D=async()=>{try{const q=await(await fetch(`/api/process-status?pids=${W.join(",")}`)).json();if(q.processes&&B){const V={};q.processes.forEach(U=>{V[U.pid]={isRunning:U.isRunning,processName:U.processName}}),h(V)}}catch(j){B&&console.error("Failed to fetch process statuses:",j)}};D();const O=setInterval(()=>void D(),5e3);return()=>{B=!1,clearInterval(O)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[C,A]=M(!1),[T,P]=M(!1);te(()=>{v.length<=3&&C&&A(!1)},[v.length,C]),te(()=>{i.length<=3&&T&&P(!1)},[i.length,T]);const _=C?v:v.slice(0,3),$=v.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[E?d("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[d("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(pt,{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..."})]}),_.map(W=>d("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[d("div",{className:"flex items-center gap-3",children:[n("div",{children:n(tt,{type:W.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(de,{to:`/entity/${W.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:W.name}),W.entityType&&n(Io,{type:W.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:W.filePath,children:W.filePath})]})]}),n("button",{onClick:a,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},W.sha)),$&&!C&&d("button",{onClick:()=>A(!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"]}),C&&$&&n("button",{onClick:()=>A(!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&&k&&k.length>0&&p&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:k.map(W=>{var U,Z,z,L;if(!W.id)return null;const B=(Z=(U=W.metadata)==null?void 0:U.screenshotPaths)==null?void 0:Z[0],D=(z=W.metadata)==null?void 0:z.noScreenshotSaved,O=B&&!D,j=(L=u==null?void 0:u.scenarios)==null?void 0:L.find(J=>J.name===W.name),V=j&&j.screenshotStartedAt&&!j.screenshotFinishedAt||!O&&!D;return n(de,{to:`/entity/${p.sha}/scenarios/${W.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:V?"#f9f9f9":void 0,borderColor:V?"#efefef":"#ccc"},children:O?n(Ge,{screenshotPath:B,alt:W.name,className:"w-full h-full object-contain bg-gray-100"}):V?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Do,{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"})},W.id)})}),N&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:N}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-2",children:[d("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(ur,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(S||((I=m[t.analyzerPid])==null?void 0:I.isRunning))&&n(ur,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(ur,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(w||((R=m[t.capturePid])==null?void 0:R.isRunning))&&n(ur,{variant:"running"})]}),(((Y=m[t==null?void 0:t.analyzerPid])==null?void 0:Y.isRunning)||((H=m[t==null?void 0:t.capturePid])==null?void 0:H.isRunning))&&n("button",{onClick:()=>{const W=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(O=>{var j;return!!O&&((j=m[O])==null?void 0:j.isRunning)});if(W.length===0)return;const B=W.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${B})?`))return;y({isKilling:!0,current:1,total:W.length}),(async()=>{for(let O=0;O<W.length;O++){const j=W[O];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:j,commitSha:o||""})})}catch(q){console.error(`Failed to kill process ${j}:`,q)}O<W.length-1&&y({isKilling:!0,current:O+2,total:W.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Pi,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),d("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(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"}),"."]})]})]}),d(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&&d("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),d("div",{className:"flex flex-col gap-4",children:[(T?i:i.slice(0,3)).map(W=>{var O;const B=(O=W.analyses)==null?void 0:O[0],D=(B==null?void 0:B.scenarios)||[];return B==null||B.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:d("div",{className:"flex flex-col gap-[15px]",children:[d("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(tt,{type:W.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[n(de,{to:`/entity/${W.sha}`,className:"hover:underline cursor-pointer",title:W.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:W.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:W.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:W.filePath,children:W.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:a,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),D.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:D.map(j=>{var Z,z,L;if(!j.id)return null;const q=(z=(Z=j.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:z[0],V=(L=j.metadata)==null?void 0:L.noScreenshotSaved,U=q&&!V;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(de,{to:`/entity/${W.sha}/scenarios/${j.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:U?"#f3f4f6":"#FAFAFA",borderColor:U?"#d1d5db":"#BCCDD3",borderStyle:U?"solid":"dashed"},onMouseEnter:J=>{U&&(J.currentTarget.style.borderColor="#005C75",J.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:J=>{J.currentTarget.style.borderColor=U?"#d1d5db":"#BCCDD3",J.currentTarget.style.boxShadow="none"},children:U?n(Ge,{screenshotPath:q,alt:j.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:j.name})]},j.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},W.sha)}),i.length>3&&!T&&d("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:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),T&&i.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 Ax({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(nd,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),d(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,o]=M(null),[a,i]=M(null),[l,c]=M(null),[p,u]=M(!1),[m,h]=M(!1),[f,y]=M(new Set),g=ht();te(()=>{e.length<=3&&m&&h(!1)},[e.length,m]);const x=k=>{o(k)},v=(k,N)=>{k.preventDefault(),i(N)},b=async(k,N)=>{if(k.preventDefault(),!s){i(null);return}const C=e.findIndex(P=>P.id===s);if(C===-1){o(null),i(null);return}if(C===N){o(null),i(null);return}const A=C<N?"down":"up",T=Math.abs(N-C);u(!0);try{for(let P=0;P<T;P++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:A})});g.revalidate()}catch(P){console.error("Failed to reorder job:",P)}finally{u(!1),o(null),i(null)}},w=()=>{p||(o(null),i(null))},S=async k=>{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:k})}),window.location.reload()}catch(N){console.error("Failed to cancel job:",N)}},E=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(k){console.error("Failed to cancel jobs:",k)}};return d("div",{children:[d("div",{className:"flex items-center justify-between mb-4",children:[d("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void E(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),d("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(k=>{var $,I,R,Y;const N=e.findIndex(H=>H.id===k.id),C=l===N,A=s===k.id,T=a===N,P=f.has(k.id),_=(($=k.entities)==null?void 0:$.length)>0?P?k.entities:k.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:A||p?.5:1,transform:T&&s!==null&&!A?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:p?"not-allowed":A?"grabbing":"grab"},onMouseEnter:()=>c(N),onMouseLeave:()=>c(null),draggable:!p,onDragStart:H=>{x(k.id),H.dataTransfer.effectAllowed="move"},onDragOver:H=>v(H,N),onDrop:H=>void b(H,N),onDragEnd:w,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(rd,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",N+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[_.length>0?d(ue,{children:[_.map(H=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(tt,{type:H.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",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(Io,{type:H.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:H.filePath})]})]})})},H.sha)),((I=k.entities)==null?void 0:I.length)>3&&n("button",{onClick:()=>{y(H=>{const W=new Set(H);return W.has(k.id)?W.delete(k.id):W.add(k.id),W})},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:P?"Show less":`+${k.entities.length-3} more ${k.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Cr,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((R=k.entityNames)==null?void 0:R[0])||(k.type==="analysis"?"Analysis Job":k.type==="recapture"?"Recapture Job":k.type==="debug-setup"?"Debug Setup":k.type.charAt(0).toUpperCase()+k.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((Y=k.filePaths)==null?void 0:Y[0])||(k.filePaths&&k.filePaths.length>1?`${k.filePaths.length} files`:k.entityShas&&k.entityShas.length>0?`${k.entityShas.length} ${k.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[C&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(sd,{size:20})}),n("button",{onClick:()=>void S(k.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"})]})]})]},k.id)}),e.length>3&&!m&&d("button",{onClick:()=>h(!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:()=>h(!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 Px({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:o,onShowLogs:a}){if(t===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(od,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),d(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,l]=M(!1),c=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{c.push({...m,runCreatedAt:u.createdAt})})});const p=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[p.map(u=>{var y;const m=(y=u.analyses)==null?void 0:y[0],h=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(tt,{type:u.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("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:a,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),h.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[h.slice(0,8).map(g=>{var w,S,E;if(!g.id)return null;const x=(S=(w=g.metadata)==null?void 0:w.screenshotPaths)==null?void 0:S[0],v=(E=g.metadata)==null?void 0:E.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(Ge,{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)}),h.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",h.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),c.length>3&&!i&&d("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const _x=We(function(){const t=Ve(),r=ki(),[s,o]=M(!1);gt({source:"activity-page"});const a=r.tab||"current";return t?d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(kx,{activeTab:a,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),a==="current"&&n(Ex,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),a==="queued"&&n(Ax,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),a==="historic"&&n(Px,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:a,onShowLogs:()=>o(!0)}),s&&t.projectSlug&&n(Ft,{projectSlug:t.projectSlug,onClose:()=>o(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),jx=Object.freeze(Object.defineProperty({__proto__:null,default:_x,loader:Sx,meta:Cx},Symbol.toStringTag,{value:"Module"}));async function nc(e,t,r){var S,E;await ze();const s=await jt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const o=pe();if(!o)throw new Error("Project root not found");const a=F.join(o,".codeyam","config.json"),i=JSON.parse(K.readFileSync(a,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=Gr(l);try{K.writeFileSync(c,"","utf8")}catch{}const{project:p}=await $e(l),u=((S=p.metadata)==null?void 0:S.packageManager)||"npm",m=3112,h=mt(l),f=((E=p.metadata)==null?void 0:E.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=ju({filePath:s.filePath,webapps:f,environmentVariables:y,port:m,packageManager:u});await wn(e,k=>{if(k&&(k.readyToBeCaptured=!0,k.scenarios))for(const N of k.scenarios)(!t||N.name===t)&&(delete N.screenshotStartedAt,delete N.screenshotFinishedAt,delete N.interactiveStartedAt,delete N.interactiveFinishedAt,delete N.error,delete N.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,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:h}]},{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 ${h}`,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:h,projectSlug:l,port:m,packageManager:u,framework:g.framework,instructions:b}}async function Mx({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),o=r.searchParams.get("scenarioId")||void 0;if(!s)return Q({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let a=t.analysisQueue;if(a||(a=await Tt()),!a)return Q({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:o});try{const i=await nc(s,o,a);return Q({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),Q({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Tx({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Tt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("scenarioId");if(!o)return Q({error:"Missing required field: analysisId"},{status:400});const i=await nc(o,a,r);return Q({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const o=s instanceof Error?s.message:String(s),a=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",a),Q({error:"Failed to setup debug environment",details:o},{status:500})}}const $x=Object.freeze(Object.defineProperty({__proto__:null,action:Tx,loader:Mx},Symbol.toStringTag,{value:"Module"}));function Rx({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=pe()||process.cwd(),o=F.resolve(s,r);if(!o.startsWith(s+F.sep)&&o!==s)return new Response("Path outside project root",{status:403});try{const a=K.readFileSync(o,"utf8");return new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const Ix=Object.freeze(Object.defineProperty({__proto__:null,loader:Rx},Symbol.toStringTag,{value:"Module"})),Dx=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function rc(e){const t=Ed("sha256",Dx);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function Ox(e,t){return t===rc(e)}async function Lx({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return Q({success:!1,error:"Unlock code is required"},{status:400});const s=await Te();return s?Ox(s,r)?(await xn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),Q({success:!0})):Q({success:!1,error:"Invalid unlock code"},{status:400}):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),Q({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const Fx=Object.freeze(Object.defineProperty({__proto__:null,action:Lx},Symbol.toStringTag,{value:"Module"}));async function zx({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Tt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("analysisId"),a=s.get("defaultWidth");if(!o||!a)return Q({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(a,10);if(isNaN(i)||i<320||i>3840)return Q({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const l=await x0(o,i,r);return console.log("[API] Recapture queued",l),Q({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),Q({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const Bx=Object.freeze(Object.defineProperty({__proto__:null,action:zx},Symbol.toStringTag,{value:"Module"}));function Yx(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(Ux).map(o=>o===""?[]:o.split("/")).reduce((o,a)=>{const i=[];for(let l=0;l<Math.min(o.length,a.length)&&o[l]===a[l];l++)i.push(o[l]);return i}).join("/")}function Ux(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(Wx(s))r.pop();else break}return r.join("/")}function Wx(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function Jx({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=Yx(r),o=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:o})}const Hx=Object.freeze(Object.defineProperty({__proto__:null,loader:Jx},Symbol.toStringTag,{value:"Module"}));function Vx(e,t){var i,l,c,p,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=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||h?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const o=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((p=e.metadata)!=null&&p.previousVersionWithAnalyses)||o){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 Gx(e){return Vx(e).hasOutdatedSimulations}function ss(e,t,r,s,o){var H,W,B,D,O,j,q,V;const a=(H=t==null?void 0:t.scenarios)==null?void 0:H.find(U=>U.name===e.name),i=!!(a!=null&&a.startedAt),l=!!(a!=null&&a.screenshotStartedAt),c=!!(a!=null&&a.screenshotFinishedAt),p=!!(a!=null&&a.finishedAt),u=1800*1e3,m=l&&!c&&(a==null?void 0:a.screenshotStartedAt)&&Date.now()-new Date(a.screenshotStartedAt).getTime()>u,h=!!((B=(W=e.metadata)==null?void 0:W.screenshotPaths)!=null&&B[0])||!!((D=e.metadata)!=null&&D.executionResult),f=l&&!c,y=a==null?void 0:a.error,g=(j=(O=e.metadata)==null?void 0:O.executionResult)==null?void 0:j.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const U of t.errors)x.push({source:`${U.phase} phase`,message:U.message});if(t!=null&&t.steps)for(const U of t.steps)U.error&&x.push({source:U.name,message:U.error});const v=!h&&!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),S=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(a==null?void 0:a.errorStack)||(g==null?void 0:g.stack)||null,k=(s&&o?o.jobs.some(U=>{var Z;return((Z=U.entityShas)==null?void 0:Z.includes(s))||U.type==="analysis"&&U.entityShas&&U.entityShas.length===0})||((V=(q=o.currentlyExecuting)==null?void 0:q.entityShas)==null?void 0:V.includes(s)):!1)&&!i&&!b||!!(a!=null&&a.analyzing)&&!i&&!b,N=i&&!l&&!p&&!b,C=(k||N||f)&&!b,A=(k||N)&&r===!1&&!h;let T;A?T="crashed":b?T="error":h||p?T="completed":f?T="capturing":N?T="starting":k?T="queued":T="pending";let P="📷",_="pending",$=!1,I=`Not captured: ${e.name}`;const R="border-gray-300",Y=b||A?"bg-red-50":"bg-white";return b||A?(P="⚠️",_="error",I=`Error: ${A?"Analysis process crashed":w||"Unknown error"}`):k?(P="⋯",_="queued",I=`Queued: ${e.name}`):N?(P="⋯",_="starting",$=!0,I=`Starting server for ${e.name}...`):f&&!b?(P="⋯",_="capturing",$=!0,I=`Capturing ${e.name}...`):h&&(P="✓",_="completed",I=e.name),{hasError:b||A,errorMessage:A?"Analysis process crashed":w,errorStack:A?"Process terminated unexpectedly before completing analysis":S,isCapturing:f,isCaptured:h,hasCrashed:A,isAnalyzing:C,isQueued:k,isServerStarting:N,status:T,icon:P,iconType:_,shouldSpin:$,title:I,borderColor:R,bgColor:Y}}function sc({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:o=!1}){var S,E,k,N,C,A;const a=ss(e,void 0,void 0,t,void 0),i=(S=e.metadata)==null?void 0:S.executionResult,l=!!i,p=(((k=(E=e.metadata)==null?void 0:E.data)==null?void 0:k.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((C=(N=i==null?void 0:i.sideEffects)==null?void 0:N.consoleOutput)==null?void 0:C.length)||0,h=((A=i==null?void 0:i.timing)==null?void 0:A.duration)||0;let f=0;p>0&&f++,p>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=a.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?o?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=s?`border-2 ${x.border}`:"",b=Array.from({length:3},(T,P)=>n("div",{className:`w-1 h-1 rounded-full ${P<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},P)),w=a.hasError?`Error: ${a.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
287
|
+
${p} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
|
|
288
|
+
${h}ms`:`Not executed: ${e.name}`;return d(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:T=>T.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:a.hasError?"⚠":l?"ƒ":"○"}),l&&!a.hasError&&d("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:p}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!a.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),l&&!a.hasError&&h>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:h>1e3?`${Math.round(h/1e3)}s`:`${h}ms`}),l&&!a.hasError&&m>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function no({size:e=24,className:t=""}){return d("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Qa({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:o,size:a="medium",cacheBuster:i,className:l="",viewMode:c}){var g,x;if(t.entityType==="library")return n(sc,{scenario:e,entitySha:t.sha,size:a==="small"?"small":"medium"});const u=ss(e,r,o,t.sha,s),m=a==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:a==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},h=`relative ${m.containerClass} ${l}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${v}/${c}`: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:`${h} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ge,{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:a==="small"?16:a==="large"?24:20,strokeWidth:2},b=n(Do,{size:a});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(no,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(ad,{...v});default:return b}};return n(de,{to:f(),className:`${h} ${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 hn=70;function qx({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:o,cacheBuster:a,activeTab:i,entityType:l,entity:c,queueState:p,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:h,viewMode:f,setViewMode:y,isBreakdownView:g}){var $,I,R,Y,H,W;const x=be(null),[v,b]=M(new Set),[w,S]=M(!1);te(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const E=B=>`/entity/${o}/scenarios/${B}`,k=B=>{b(D=>{const O=new Set(D);return O.has(B)?O.delete(B):O.add(B),O})},N=(B,D=2)=>{const j=B.split(`
|
|
289
|
+
`).slice(0,D).join(" ").trim();return j.length>hn?j.substring(0,hn-3):(B.split(`
|
|
290
|
+
`).length>D||B.length>j.length,j)},C=ne(()=>{var D;if(!((D=r==null?void 0:r.metadata)!=null&&D.executionFlows)||!(r!=null&&r.scenarios))return null;const B=r.scenarios.filter(O=>{var j;return!((j=O.metadata)!=null&&j.sameAsDefault)});return Mo(r.metadata.executionFlows,B)},[r]),A=(C==null?void 0:C.totalFlows)||0,T=(C==null?void 0:C.coveredFlows)||0,P=(C==null?void 0:C.coveragePercentage)||0;($=c==null?void 0:c.metadata)!=null&&$.defaultWidth||(I=r==null?void 0:r.metadata)!=null&&I.defaultWidth;const _=(R=r==null?void 0:r.status)!=null&&R.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return d("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&d("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),d("div",{className:"grid grid-cols-2 gap-2",children:[d(de,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((Y=e[0])==null?void 0:Y.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(P),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(de,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((H=e[0])==null?void 0:H.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[T,"/",A]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(de,{to:g?`/entity/${o}/scenarios/${(s==null?void 0:s.id)||((W=e[0])==null?void 0:W.id)}`:`/entity/${o}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),c&&c.filePath&&n("div",{children:n(de,{to:`/entity/${o}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),_&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:_})]}),m&&(h||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((B,D)=>{const O=!g&&(s==null?void 0:s.id)===B.id,j=v.has(B.id||"");return B.id?d(de,{to:E(B.id),ref:O?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${O?"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(Qa,{scenario:B,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:a,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${j?"":"line-clamp-1"}`,children:B.name}),B.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[j?B.description:N(B.description),!j&&B.description.length>hn&&d(ue,{children:["...",n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),k(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),j&&B.description.length>hn&&n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),k(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},D):null})})}),t.length>0&&!(m&&h)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("button",{onClick:()=>S(!w),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${w?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),w&&d("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((B,D)=>{const O=!g&&(s==null?void 0:s.id)===B.id,j=v.has(B.id||"");return B.id?d(de,{to:`/entity/${o}/scenarios/${B.id}`,ref:O?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${O?"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(Qa,{scenario:B,entity:{sha:o,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:a,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${j?"":"line-clamp-1"}`,children:B.name}),B.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[j?B.description:N(B.description),!j&&B.description.length>hn&&d(ue,{children:["...",n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),k(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),j&&B.description.length>hn&&n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),k(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},D):null})})]})]})]})}function Kx({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:o,onDelete:a,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:p=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:h=null}){const[f,y]=M(""),g=async()=>{await r(f)},x=async v=>{await s(f,v),v||y("")};return d("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[d("div",{className:"border-b border-[#e1e1e1] pb-3",children:[d("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(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})]}),d("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[d("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange: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}),d("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&d("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),d("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:o,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),c&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${c.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:c}),c==="Recapture successful"&&n("div",{children:n(de,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),d("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),a&&d(ue,{children:[p?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void a(),disabled: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"}),h&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:h})]})]})]})}function Qx({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,o=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],a=p=>{var y,g,x;if(!p)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=p.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 h=((g=p.sideEffects)==null?void 0:g.fileWrites)||[];h.length>0&&(u.push(`
|
|
291
|
+
File System Operations: ${h.length} ${h.length===1?"operation":"operations"} detected`),h.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=p.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)`:""}`)})),p.error&&u.push(`
|
|
293
|
+
Error: ${p.error.name||"Error"}: ${p.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
294
|
+
`)};return d("div",{className:"flex w-full h-full gap-0",children:[d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(o,null,2)})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:a(s)})})]})]})}const Zt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function pr({scenarioId:e,analysisId:t}){const[r,s]=M(!1),[o,a]=M(!1),[i,l]=M(null),[c,p]=M(!1),u=e||t;if(!u)return null;const m=`/codeyam-diagnose ${u}`,h=async()=>{a(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{a(!1)}},f=()=>{s(!1),l(null)};return d(ue,{children:[d("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Zt.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:Zt.subtext},children:"Simply run this command in Claude Code:"}),d("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Zt.commandBoxBg,borderColor:Zt.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:Zt.commandBoxText},children:m}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(m),p(!0),setTimeout(()=>p(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:c?"#22c55e":Zt.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(ft,{size:14}):n(St,{size:14})})]}),d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void h(),disabled:o,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Zt.link},children:o?"capturing...":"please do so here"}),"."]})]}),n(Di,{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 Za=1440,mr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],wt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function oc({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:o,hasScenarios:a,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:p,queueState:u}){var G,X,le,xe,oe,me,Ce,Re,je,De,Le;const m=Oe(),[h,f]=M(!1),[y,g]=M(!1),[x,v]=M({name:"Desktop",width:Za,height:900}),[b,w]=M(Za),[S,E]=M(1),{customSizes:k,addCustomSize:N,removeCustomSize:C}=Xr(l),A=ne(()=>[...mr,...k],[k]),T=(Ee,re)=>{w(Ee);const ye=A.find(Se=>Se.width===Ee&&Se.height===re);v({name:(ye==null?void 0:ye.name)||"Custom",width:Ee,height:re})},P=Ee=>{w(Ee.width),v({name:Ee.name,width:Ee.width,height:Ee.height})},_=Ee=>{N(Ee,x.width,x.height??900),g(!1),v(re=>({...re,name:Ee}))},$=(Ee,re)=>{w(Ee);const ye=A.find(Se=>Se.width===Ee&&Se.height===re);v(Se=>({name:(ye==null?void 0:ye.name)||"Custom",width:Ee,height:Se.height}))},I=(X=(G=e==null?void 0:e.metadata)==null?void 0:G.screenshotPaths)==null?void 0:X[0],R=ne(()=>e?ss(e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u]),Y=ne(()=>{var re,ye;const Ee=[];if((re=t==null?void 0:t.status)!=null&&re.errors&&t.status.errors.length>0)for(const Se of t.status.errors)Ee.push({source:`${Se.phase} phase`,message:Se.message,stack:Se.stack});if((ye=t==null?void 0:t.status)!=null&&ye.steps)for(const Se of t.status.steps)Se.error&&Ee.push({source:Se.name,message:Se.error,stack:Se.errorStack});return Ee},[(le=t==null?void 0:t.status)==null?void 0:le.errors,(xe=t==null?void 0:t.status)==null?void 0:xe.steps]),H=(R==null?void 0:R.errorMessage)||null,W=(R==null?void 0:R.errorStack)||null,{interactiveServerUrl:B,isStarting:D,isLoading:O,showIframe:j,iframeKey:q,onIframeLoad:V}=dn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),U=ne(()=>B||null,[B]),Z=!i&&a&&e&&!((me=(oe=e.metadata)==null?void 0:oe.screenshotPaths)!=null&&me[0])&&((Re=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:Re.some(Ee=>Ee.name===e.name&&Ee.screenshotStartedAt&&!Ee.screenshotFinishedAt)),{lastLine:z}=Pt(l,i||s==="interactive"||Z||!1);if(!e){if(i&&r)return d(ue,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:d("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:Z?"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."}),z&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:z}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)})]});if(!a&&r&&!i){if(Y.length>0){const Ee=Y.length===1?((je=Y[0])==null?void 0:je.message)||"An error occurred during analysis.":`${Y.length} errors occurred during analysis.`;return d(ue,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:wt.background,border:`2px solid ${wt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(no,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:wt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",Ee," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:wt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(pr,{analysisId:t==null?void 0:t.id})})]})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:d("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{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 d(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||Z&&!I)&&!H&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:d("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[d("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:Z?`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:Z?`Taking screenshots for ${((De=t==null?void 0:t.scenarios)==null?void 0:De.length)||0} scenario${((Le=t==null?void 0:t.scenarios)==null?void 0:Le.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&d("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),z&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:d("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:z,children:z})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(I||H)||s==="interactive"&&(U||D)||s==="data"?d(ue,{children:[H&&!I&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:wt.background,border:`2px solid ${wt.border}`,maxHeight:"50vh"},role:"alert",children:d("div",{className:"flex flex-col gap-3",children:[d("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:wt.text},children:[n(no,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),d("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:wt.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:wt.text},children:H})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(pr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?d("div",{className:"flex-1 flex flex-col min-h-0",children:[U&&d("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Ym,{presets:[...mr],customSizes:k,currentWidth:x.width,currentHeight:x.height??900,scale:S,onSizeChange:T,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:C}),e&&r&&d(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"]})]}),U&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${mr[mr.length-1].width}px`,width:"100%"},children:n(wo,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:P,devicePresets:A})})}),n(ts,{scenarioId:e.id,scenarioName:e.name,iframeUrl:U,isStarting:D,isLoading:O,showIframe:j,iframeKey:q,onIframeLoad:V,onScaleChange:E,onDimensionChange:$,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(Qx,{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:(I||!H)&&n(Ge,{screenshotPath:I,cacheBuster:o,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!I?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),d("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),d("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),z&&d("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:z})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):H?d("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!c&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:d("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[d("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),d("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),d("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),d("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:H})})]}),W&&d("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:W})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(pr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):Y.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:Y,title:"Analysis Error",description:Y.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${Y.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(pr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)}),y&&n(Zr,{width:x.width,height:x.height??900,onSave:_,onCancel:()=>g(!1)})]})}function Zx({analysis:e,entitySha:t}){ht();const[r,s]=M(e);te(()=>{s(e)},[e]);const[o,a]=M(null),i=ne(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(h=>{var f;return!((f=h.metadata)!=null&&f.sameAsDefault)});return Mo(r.metadata.executionFlows,u)},[r]),l=ne(()=>i?tf(i):[],[i]),c=ne(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),p=u=>{var h;const m=((h=u.metadata)==null?void 0:h.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:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:d("div",{className:"p-6 space-y-6",children:[d("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:c.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${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"})]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",c.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:c.length===0?d("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"})]}):c.map(u=>{var f,y,g;const m=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],h=p(u);return d("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ge,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(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}),h.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:h.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:d(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"]})})]}),l.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[l.length," uncovered execution flow",l.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[l.slice(0,10).map(u=>d("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),l.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",l.length-10," more"]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=o===u.id,h=u.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>a(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:d("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),h?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&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&d("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>d("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children: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))})]}),h&&d("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children: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&&d("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Xa({hasIndirectBadge:e,onAnalyze:t}){return d(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),d("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function Xx({entity:e,history:t}){const[r,s]=M("entity"),[o,a]=M(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ne(()=>{const u=new Map;return t.forEach(m=>{m.analyses.forEach(h=>{(h.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:h,scenario:y})})})}),Array.from(u.entries()).map(([m,h])=>{var f;return{name:m,description:((f=h[0])==null?void 0:f.scenario.description)||"",versions:h.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,p=u=>{a(m=>{const h=new Set(m);return h.has(u)?h.delete(u):h.add(u),h})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),d("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:c})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?d("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,m)=>d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[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"}),d(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((h,f)=>{var g;const y=(h.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(Xa,{hasIndirectBadge:h.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):d(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[h.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=h.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[d("span",{className:"font-medium",children:["What Changed:"," "]}),h.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 S,E;const b=(E=(S=x.metadata)==null?void 0:S.screenshotPaths)==null?void 0:E[0],w=`${x.name}-${v}`;return d(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(Ge,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},w)})})})]})},h.id||f)})}):n(Xa,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,m)=>{const h=o.has(u.name),f=h?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,d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),d("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var N,C;const{version:b,analysis:w,scenario:S}=x,E=(C=(N=S.metadata)==null?void 0:N.screenshotPaths)==null?void 0:C[0],k=v===0;return d("div",{className:`flex gap-5 items-start ${k?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(de,{to:`/entity/${b.sha}/scenarios/${S.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:E?n(Ge,{screenshotPath:E,alt:S.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),d("div",{className:"flex-1 flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[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"}),k&&u.versions.length>1&&d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),d(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&&d("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&&d("button",{onClick:()=>p(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 ${h?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),h?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function ei({entity:e,analysisInfo:t,from:r}){const s=Oe(),o=s.state!=="idle",a=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),a&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(de,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:d("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ge,{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(tt,{type:e.entityType})})}),d("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(tt,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&d("div",{className:"flex items-center gap-2 mt-2",children:[d("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?d(ue,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),a&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):d(ue,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),a&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const ti=e=>{var o,a,i;const t=((o=e.analysisStatus)==null?void 0:o.status)||"not_analyzed",r=((a=e.analysisStatus)==null?void 0:a.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function eb({importedEntities:e,importingEntities:t}){const[r]=vn(),s=r.get("from"),o=Oe(),a=o.state!=="idle",i=e.length>0,l=t.length>0,c=h=>h.filter(f=>f.entityType==="visual"||f.entityType==="library"),p=h=>{const f=c(h);f.length!==0&&o.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=c(e).length>0,m=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>p(e),disabled:a,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:a?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(h=>n(ei,{entity:h,analysisInfo:ti(h),from:s},h.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>p(t),disabled:a,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:a?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(h=>n(ei,{entity:h,analysisInfo:ti(h),from:s},h.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 tb({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(eb,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function nb({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Hn,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Hn({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:o,showInlineToggle:a=!1}){const[i,l]=M(r||t<2);if(te(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const c=typeof e;if(c==="string")return d("span",{className:"text-green-600",children:['"',e,'"']});if(c==="number")return n("span",{className:"text-blue-600",children:e});if(c==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","["]}),!i&&d("span",{children:[e.length,"]"]})]}),i?d(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((p,u)=>n("div",{className:"py-0.5",children:n(Hn,{data:p,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const p=Object.keys(e);if(p.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=h=>Array.isArray(h)&&h.length>0;return d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[p.length,"}"]})]}),i?d(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:p.map(h=>{const f=e[h],y=u(f),g=m(f);return n("div",{className:"py-0.5",children:y?n(Oo,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(Lo,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(ue,{children:[d("span",{className:"text-orange-600",children:[h,": "]}),n(Hn,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},h)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Oo({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:o}){const[a,i]=M(s||r<2),l=Object.keys(t);return te(()=>{i(s||r<2)},[s,r]),d(ue,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!a),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:a?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!a&&d("span",{className:"text-gray-600",children:[l.length,"}"]})]}),a&&d(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const p=t[c],u=p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=Array.isArray(p)&&p.length>0;return n("div",{className:"py-0.5",children:u?n(Oo,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:o}):m?n(Lo,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:o}):d(ue,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(Hn,{data:p,depth:r+2,defaultExpanded:s,maxDepth:o})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Lo({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:o}){const[a,i]=M(s||r<2);return te(()=>{i(s||r<2)},[s,r]),d(ue,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!a),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:a?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!a&&d("span",{className:"text-gray-600",children:[t.length,"]"]})]}),a&&d(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const p=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:p?n(Oo,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:o}):u?n(Lo,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:o}):n(Hn,{data:l,depth:r+2,defaultExpanded:s,maxDepth:o})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function js({label:e,count:t,isActive:r,onClick:s,badgeColorActive:o,badgeTextActive:a}){return d("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${o} ${a}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function ni({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 ri({call:e,scenarioName:t}){const[r,s]=M(!1),[o,a]=M("system"),i=h=>new Date(h).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=h=>h?`$${h.toFixed(4)}`:null,c=(h,f)=>{if(!h&&!f)return null;const y=[];return h&&y.push(`${h.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},p=ne(()=>{var h,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(h=v.choices)==null?void 0:h[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=ne(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=ne(()=>{var h;if(t)return t;try{const f=JSON.parse(e.props);return((h=f==null?void 0:f.scenario)==null?void 0:h.name)||null}catch{return null}},[e.props,t]);return d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),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"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>a("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>a("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>a("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>a("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),o&&d("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),o==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),o==="response"&&d("div",{children:[e.error&&d("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:p})]}),o==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!o&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const si=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function rb({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:o}){var w,S,E,k,N,C,A,T,P;const[a,i]=M("entity"),[l,c]=M("analysis"),[p,u]=M(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,h]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ne(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const _=[...o.entityCalls,...o.analysisCalls],$=_.filter(R=>R.object_type==="entity"||si.includes(R.prompt_type)),I=_.filter(R=>R.object_type!=="entity"&&!si.includes(R.prompt_type));return $.sort((R,Y)=>Y.created_at-R.created_at),I.sort((R,Y)=>Y.created_at-R.created_at),{entityLlmCalls:$,scenarioLlmCalls:I,totalLlmCalls:_.length}},[o]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(w=e==null?void 0:e.metadata)==null?void 0:w.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(S=t==null?void 0:t.metadata)==null?void 0:S.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(k=(E=e==null?void 0:e.metadata)==null?void 0:E.isolatedDataStructure)==null?void 0:k.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(N=t==null?void 0:t.metadata)==null?void 0:N.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(C=e==null?void 0:e.metadata)==null?void 0:C.importedExports,"External Dependencies":(A=e==null?void 0:e.metadata)==null?void 0:A.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(T=t==null?void 0:t.metadata)==null?void 0:T.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(_=>_.data!==void 0&&_.data!==null).length;let b=null;if(a==="entity"){const _=x.find($=>$.id===l);_&&_.data!==void 0&&_.data!==null&&(b={title:_.title,description:_.description,data:_.data})}else if(a==="scenarios"&&p){const _=r.find($=>($.id||$.name)===p.scenarioId);_&&(b={title:_.name,description:_.description||"Scenario data and configuration",data:_.metadata})}return d("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:d("div",{className:"flex border-b border-gray-200 relative",children:[n(js,{label:"Entity",isActive:a==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(js,{label:"Scenarios",count:r.length,isActive:a==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(js,{label:"LLM Calls",count:g,isActive:a==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((P=t==null?void 0:t.metadata)==null?void 0:P.analyzerVersion)&&d("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),a==="llm-calls"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>h("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,")"]}),d("button",{onClick:()=>h("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(_=>n(ri,{call:_},_.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(_=>n(ri,{call:_},_.id))})]}):d("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:a==="entity"?d(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(_=>{const $=_.data!==void 0&&_.data!==null;return n(ni,{label:_.title,isActive:l===_.id,onClick:()=>c(_.id),disabled:!$},_.id)})})]}):d(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(_=>{const $=_.id||_.name,I=(p==null?void 0:p.scenarioId)===$;return n(ni,{label:_.name,isActive:I,onClick:()=>u({scenarioId:$})},$)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(sb,{title:b.title,description:b.description,data:b.data}):a==="scenarios"&&r.length===0?n(oi,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):a==="entity"?n(oi,{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 oi({title:e,description:t,onAnalyze:r}){return d("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function sb({title:e,description:t,data:r}){const[s,o]=M(!0);return d(ue,{children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),d("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>o(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>o(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(Mt,{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(nb,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function ob({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const o=Oe();return te(()=>{if(e!=null&&e.sha&&o.state==="idle"&&!o.data){const a=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;o.load(a)}},[e==null?void 0:e.sha,t==null?void 0:t.id,o.state,o.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(rb,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:o.data})})}const ab={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},ib={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},lb=2e3,cb=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 db({entity:e,entityCode:t}){const r=Dr(),s=be(null);return te(()=>{const o=r.hash;if(!o||!s.current)return;const a=o.match(/^#L(\d+)$/);if(!a)return;const i=parseInt(a[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const c=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=c},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:d("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(Mt,{content:t,label:"Copy Code",duration:lb,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(Dd,{language:cb(e==null?void 0:e.filePath),style:Od,showLineNumbers:!0,customStyle:ab,lineNumberStyle:ib,wrapLines:!0,lineProps:o=>({"data-line-number":o,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const ub=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function pb({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:o,defaultShouldRevalidate:a}){return r.pathname===s.pathname&&r.search===s.search?a:!!(e.sha!==t.sha||o)}async function mb({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const a=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),c=l[0]||"scenarios",p=l[1]||null,u=l[2]||null,m=r.analysisQueue,h=m?m.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([an(s),Te(),Nn(),hp(pe()||process.cwd())]),v=f?await Jr(f):null,b=f?await Zi(f.sha):null;let w={importedEntities:[],importingEntities:[]},S=null,E=[];f&&(w=await Xi(f),S=await el(f),E=await nl(f));const k=!!(f&&E.length>0&&E[0].sha!==f.sha),N=E.length>0?E[0].sha:null,C=!!(E.length>0&&E[0].analyses&&E[0].analyses.length>0),A=f?await tl(f):!1;return Q({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:a,relatedEntities:w,entityCode:S??void 0,hasNewerVersion:k,newestEntitySha:N,newestVersionHasAnalysis:C,fileModifiedSinceEntity:A,history:E,tab:c,scenarioId:p,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:h})}const hb=We(function(){var pn,Ko,Qo,Zo,Xo,ea,ta,na,ra,sa,oa,aa,ia,la,ca;const t=Ve(),o=(ki()["*"]||"").split("/").filter(Boolean),a=o[0]||"scenarios",i=o[1]||null,l=o[2]||null,c=t.entity,p=t.analysis,u=t.currentEntityAnalysis,m=u||p,h=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,S=t.currentCommit,E=t.hasAnApiKey,k=t.queueState;(pn=m==null?void 0:m.status)==null||pn.errors;const N=(m==null?void 0:m.scenarios)||[],C=N.filter(ce=>{var Pe;return!((Pe=ce.metadata)!=null&&Pe.sameAsDefault)}),A=N.filter(ce=>{var Pe;return(Pe=ce.metadata)==null?void 0:Pe.sameAsDefault}),T=Et(),P=be(null);te(()=>{P.current===null&&(P.current=window.history.length)},[]);const _=()=>{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)T("/");else{const Pe=window.history.length,Xe=P.current;if(Xe!==null&&Pe>Xe){const Fe=Pe-Xe+1;T(-Fe)}else T(-1)}},$=!!k.currentlyExecuting,I=a,R=(Ko=S==null?void 0:S.metadata)==null?void 0:Ko.currentRun,Y=!!(R!=null&&R.createdAt)&&!(R!=null&&R.analysisCompletedAt),H=!!(c!=null&&c.sha&&((Qo=R==null?void 0:R.currentEntityShas)!=null&&Qo.includes(c.sha))),W=!!(c!=null&&c.sha&&((Xo=(Zo=k.currentlyExecuting)==null?void 0:Zo.entityShas)!=null&&Xo.includes(c.sha))),B=!!(c!=null&&c.sha&&((ea=k.jobs)!=null&&ea.some(ce=>{var Pe;return(Pe=ce.entityShas)==null?void 0:Pe.includes(c.sha)}))),D=H||W||B,O=D&&((ta=m==null?void 0:m.status)==null?void 0:ta.finishedAt)!=null&&C.length>0&&m.entitySha!==(c==null?void 0:c.sha),j=ne(()=>{if(I!=="scenarios")return null;if(i){const ce=C.find(Pe=>Pe.id===i);if(ce)return ce}return C.length>0&&!D?C[0]:null},[I,i,C,D]),q=((sa=(ra=(na=j==null?void 0:j.metadata)==null?void 0:na.executionResult)==null?void 0:ra.error)==null?void 0:sa.message)||((ia=(aa=(oa=m==null?void 0:m.status)==null?void 0:oa.errors)==null?void 0:aa[0])==null?void 0:ia.message);gt({source:j?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:j==null?void 0:j.id,analysisId:m==null?void 0:m.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:j==null?void 0:j.name,errorMessage:q});const[V,U]=M(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");te(()=>{l&&l!==V&&l!=="edit"&&U(l)},[l]);const Z=l==="edit",[z,L]=M(!1),[J,G]=M(!1),[X,le]=M(null),[xe,oe]=M(!1),[me,Ce]=M(!1),[Re,je]=M(null),[De,Le]=M(null),[Ee,re]=M(0),{interactiveServerUrl:ye,isStarting:Se,isLoading:ct,showIframe:he,iframeKey:Be,onIframeLoad:Je}=dn({analysisId:m==null?void 0:m.id,scenarioId:j==null?void 0:j.id,scenarioName:j==null?void 0:j.name,projectSlug:h,enabled:Z&&!!j,refreshTrigger:Ee}),[yt,Go]=M(!1),[Jt,qo]=M(""),[dt,$t]=M(!1),[En,un]=M(Date.now()),[xt,An]=M(!1),Qe=Oe(),bt=Oe(),qe=Oe(),Ue=ht(),Ht=k.jobs.some(ce=>{var Pe;return(c==null?void 0:c.sha)&&((Pe=ce.entityShas)==null?void 0:Pe.includes(c.sha))||ce.type==="analysis"&&ce.commitSha===(S==null?void 0:S.sha)&&ce.entityShas&&ce.entityShas.length===0}),Pn=D,Xn=((la=c==null?void 0:c.metadata)==null?void 0:la.defaultWidth)||((ca=m==null?void 0:m.metadata)==null?void 0:ca.defaultWidth)||1440,is=Math.round(Xn*(900/1440));Qe.state==="submitting"||Qe.state,ne(()=>{var ce;return!!((ce=j==null?void 0:j.metadata)!=null&&ce.interactiveExamplePath)},[j]);const{isCompleted:er}=Pt(h,dt);te(()=>{Qe.state==="idle"&&Qe.data&&(Qe.data.success?setTimeout(()=>{un(Date.now()),Ue.revalidate(),$t(!1)},1500):Qe.data.error&&($t(!1),alert(`Recapture failed: ${Qe.data.error}`)))},[Qe.state,Qe.data,Ue]),te(()=>{dt&&er&&setTimeout(()=>{un(Date.now()),Ue.revalidate(),$t(!1)},1500)},[dt,er,Ue]),te(()=>{bt.state==="idle"&&bt.data&&(bt.data.success?setTimeout(()=>{un(Date.now()),Ue.revalidate(),$t(!1)},1500):bt.data.error&&($t(!1),alert(`Recapture failed: ${bt.data.error}`)))},[bt.state,bt.data,Ue]);const Rt=()=>{c&&(g&&x&&x!==c.sha?(T(`/entity/${x}/scenarios`),setTimeout(()=>{qe.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):qe.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};te(()=>{qe.state==="idle"&&qe.data&&(qe.data.success?Ue.revalidate():qe.data.error&&alert(`Analysis failed: ${qe.data.error}`))},[qe.state,qe.data,c==null?void 0:c.sha,Ue]),te(()=>{const ce=setTimeout(()=>{Ue.revalidate()},500);return()=>clearTimeout(ce)},[]),te(()=>{if(Y||Pn){const ce=setInterval(()=>{Ue.revalidate()},3e3);return()=>clearInterval(ce)}},[Y,Pn,Ue]);const tr=(ce,Pe)=>ce==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${ce}`,ls=(ce,Pe)=>`/entity/${c==null?void 0:c.sha}/scenarios/${ce}/${Pe}`,se=ce=>{U(ce),j!=null&&j.id&&(ce==="interactive"?T(`/entity/${c==null?void 0:c.sha}/scenarios/${j.id}/fullscreen`,{replace:!0}):T(ls(j.id,ce),{replace:!0}))},Ne=async ce=>{var Pe,Xe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ce,hasSelectedScenario:!!j,hasAnalysis:!!m}),!j||!m){const Fe="Error: No scenario or analysis available";console.error("[EntityDetail]",Fe),le(Fe);return}L(!0),le(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ce,scenarioId:j.id,scenarioName:j.name,currentData:j.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:j.name,editingMockData:De||((Xe=j.metadata)==null?void 0:Xe.data)})}),vt=await Fe.json();if(!Fe.ok||!vt.success)throw new Error(vt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",vt.data),Le(vt.data);const nr=(m.scenarios||[]).map(Ke=>Ke.id===j.id?{...Ke,metadata:{...Ke.metadata,data:vt.data}}:Ke),_n=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:nr})}),st=await _n.json();if(!_n.ok||!st.success)throw console.error("[EntityDetail] Temp save failed:",st),new Error(st.error||"Failed to apply preview");if(le("Generating preview. Capturing screenshot..."),ye){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ye});const Ke=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ye,scenarioId:j.id,projectId:m.projectId,viewportWidth:1440})}),jn=await Ke.json();!Ke.ok||!jn.success?(console.error("[EntityDetail] Direct capture failed:",jn),le("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),le('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ke=new FormData;Ke.append("analysisId",m.id||""),Ke.append("scenarioId",j.id||"");const jn=await fetch("/api/recapture-scenario",{method:"POST",body:Ke}),ds=await jn.json();!jn.ok||!ds.success?(console.warn("[EntityDetail] Recapture failed:",ds.error),le("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",ds.jobId),le('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}re(Ke=>Ke+1),Ue.revalidate()}catch(Fe){console.error("Error applying changes:",Fe),le(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{L(!1)}},ke=async(ce,Pe)=>{var Xe;if(!j||!m){le("Error: No scenario or analysis available");return}G(!0),le(null),console.log("[EntityDetail] Saving scenario to database",{description:ce,saveAsNew:Pe});try{const Fe=De||((Xe=j.metadata)==null?void 0:Xe.data);let vt;if(Pe){const st={...j,id:`${j.name}-${Date.now()}`,name:`${j.name} (Copy)`,metadata:{...j.metadata,data:Fe},description:ce||j.description};vt=[...m.scenarios||[],st]}else vt=(m.scenarios||[]).map(st=>st.id===j.id?{...st,metadata:{...st.metadata,data:Fe},description:ce||st.description}:st);const nr=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:vt})}),_n=await nr.json();if(!nr.ok||!_n.success)throw new Error(_n.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),le(Pe?"New scenario created successfully":"Scenario saved successfully"),Le(null),Ue.revalidate()}catch(Fe){console.error("Error saving scenario:",Fe),le(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{G(!1)}},Ie=()=>{j!=null&&j.id&&(c!=null&&c.sha)&&T(`/entity/${c.sha}/scenarios/${j.id}/dev`)},Ze=async()=>{var ce;if(!(j!=null&&j.id)){je("Cannot delete scenario without ID");return}oe(!0),je(null);try{const Pe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:j.id,screenshotPaths:((ce=j.metadata)==null?void 0:ce.screenshotPaths)||[]})}),Xe=await Pe.json();if(!Pe.ok||!Xe.success)throw new Error(Xe.error||"Failed to delete scenario");T(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(Pe){console.error("[EntityDetail] Error deleting scenario:",Pe),je(Pe instanceof Error?Pe.message:"Failed to delete scenario"),Ce(!1)}finally{oe(!1)}},Vt=m&&c&&m.entitySha!==c.sha,cs=c?Gx(c):!1;return n(es,{children:d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:_,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:c==null?void 0:c.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:c==null?void 0:c.filePath,children:c==null?void 0:c.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:C.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:tr(ce.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${I===ce.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:I===ce.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("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 ${I===ce.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ce.count})]})},ce.id))})]})}),(g||Vt&&!u||b&&cs)&&!D&&!Ht&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:d("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Vt&&!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.":Vt?"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:Rt,disabled:qe.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=>{qe.state==="idle"&&(ce.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ce=>{qe.state==="idle"&&(ce.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[I==="scenarios"&&d(ue,{children:[Z&&j?n(Kx,{scenario:j,entitySha:(c==null?void 0:c.sha)||"",onApply:Ne,onSave:ke,onEditMockData:Ie,onDelete:Ze,isApplying:z,isSaving:J,saveMessage:X,showDeleteConfirm:me,onShowDeleteConfirm:Ce,isDeleting:xe,deleteError:Re}):n(qx,{scenarios:C,hiddenScenarios:A,analysis:m,selectedScenario:j,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:En,activeTab:I,entityType:c==null?void 0:c.entityType,entity:c,queueState:k,processIsRunning:$,isEntityAnalyzing:D,areScenariosStale:O,viewMode:V,setViewMode:se,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Zx,{analysis:m??null,entitySha:(c==null?void 0:c.sha)||""}):Z&&j?n(ts,{scenarioId:j.id||j.name,scenarioName:j.name,iframeUrl:ye,isStarting:Se,isLoading:ct,showIframe:he,iframeKey:Be,onIframeLoad:Je,projectSlug:h,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[j&&d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:j.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Xn," × ",is]})]}),d("div",{className:"flex items-center gap-2",children:[n(de,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${j.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),d("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),d(de,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${j.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),d(de,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${j.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(oc,{selectedScenario:j,analysis:m,entity:c,viewMode:V,cacheBuster:En,hasScenarios:C.length>0,isAnalyzing:Pn,projectSlug:h,hasAnApiKey:E,processIsRunning:$,queueState:k})]})]}),I==="related"&&n(tb,{relatedEntities:f}),I==="data"&&n(ob,{entity:c,analysis:m,scenarios:C,onAnalyze:Rt}),I==="code"&&n(db,{entity:c,entityCode:y}),I==="history"&&n(Xx,{entity:c,history:w})]}),xt&&h&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>An(!1),children:d("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ce=>ce.stopPropagation(),children:[d("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>An(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(Ft,{projectSlug:h,onClose:()=>An(!1)})})]})})]})})}),fb=Object.freeze(Object.defineProperty({__proto__:null,default:hb,loader:mb,meta:ub,shouldRevalidate:pb},Symbol.toStringTag,{value:"Module"}));async function gb(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:o,queue:a}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await ze();const i=pe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),c=JSON.parse(await we.readFile(l,"utf8")),{projectSlug:p,branchId:u}=c;if(!p||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${p}, Branch: ${u}`);const m=Gr(p);try{await we.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:h,branch:f}=await $e(p);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await et({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 up(h,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Lt({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)&&Np(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=a.enqueue({type:"analysis",commitSha:x.sha,projectSlug:p,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...s?{context:s}:{},...o?{scenarioCount:o}:{}});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 yb({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Tt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),o=s.get("entitySha"),a=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),c=s.get("scenarioCount");let p;if(a)p=a.split(",").filter(Boolean);else if(o)p=[o];else return Q({error:"Missing required field: entitySha or entityShas"},{status:400});if(p.length===0)return Q({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${p.length} entity(ies)`);const u=await et({shas:p}),h=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await gb({entityShas:p,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),Q({success:!0,message:`Analysis queued for ${p.length} entity(ies)`,entityCount:p.length,fileCount:h,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),Q({error:"Failed to start analysis",details:s.message},{status:500})}}const xb=Object.freeze(Object.defineProperty({__proto__:null,action:yb},Symbol.toStringTag,{value:"Module"}));function bb(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function ac(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const o=t.getHours(),a=t.getMinutes(),i=o>=12?"pm":"am",l=o%12||12,c=a.toString().padStart(2,"0");return`Today, ${l}:${c} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function ot(e,t=[],r=!1){var u,m;if(t.some(h=>{var f,y;return!!((f=h.entityShas)!=null&&f.includes(e.sha)||(y=h.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const o=e.analyses[0];if(!(((u=o.status)==null?void 0:u.scenarios)&&o.status.scenarios.length>0&&o.status.scenarios.some(h=>h.screenshotFinishedAt||h.finishedAt))||o.entitySha!==e.sha)return"not-analyzed";const i=o.createdAt?new Date(o.createdAt).getTime():0,l=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,c=o.scenarios||[],p=c.some(h=>{var f,y,g;return((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=h.metadata)==null?void 0:g.executionResult)});return i>=l?c.length>0&&p?c.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":c.length>0?"incomplete":"not-analyzed":"out-of-date"}const vb=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function wb({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},o=await cn();return Q({entities:o||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),Q({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Nb=We(function(){const t=Ve(),r=t.entities,s=t.queueState;gt({source:"simulations-page"});const[o,a]=M(""),[i,l]=M("visual"),c=ne(()=>{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(S=>{var E;return!((E=S.metadata)!=null&&E.sameAsDefault)}).map(S=>{var P,_,$,I,R;const E=(_=(P=S.metadata)==null?void 0:P.screenshotPaths)==null?void 0:_[0],k=($=S.metadata)==null?void 0:$.noScreenshotSaved,N=E&&!k,C=(R=(I=v.status)==null?void 0:I.scenarios)==null?void 0:R.find(Y=>Y.name===S.name),A=C&&C.screenshotStartedAt&&!C.screenshotFinishedAt;let T;return N?T="completed":A?T="capturing":T="error",{scenarioName:S.name,scenarioDescription:S.description||"",screenshotPath:E||"",scenarioId:S.id,state:T}}).filter(S=>S.state==="completed"||S.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]),p=ne(()=>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(S=>{var E,k;return(k=(E=S.metadata)==null?void 0:E.screenshotPaths)==null?void 0:k[0]}))}),[r]),u=ne(()=>c.filter(({entity:g})=>{const x=!o||g.name.toLowerCase().includes(o.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[c,o,i]),m=ne(()=>p.filter(g=>{const x=!o||g.name.toLowerCase().includes(o.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[p,o,i]),h=ae(g=>{a(g.target.value)},[]),f=ae(g=>{l(g.target.value)},[]),y=c.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:d("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative",children:[d("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(lt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Vn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:o,onChange:h})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:d("div",{className:"flex items-center py-3",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),d("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(Cb,{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(Sb,{entity:g},g.sha)))]})]})})});function Cb({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=Et(),o=Oe(),[a,i]=M(!1),l=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),c=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},p=()=>{i(!0),o.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};te(()=>{o.state==="idle"&&a&&i(!1)},[o.state,a]);const u=ot(e,r),m=bb(u),h=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(tt,{type:e.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[d(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," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[h&&n(ue,{children:a||o.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(pt,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:p,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter: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(Ge,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Do,{size:"medium"}):null})}),d("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:d("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&d(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 Sb({entity:e}){const t=Oe(),[r,s]=M(!1),o=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return te(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:o,children:d("div",{className:"px-5 py-4 flex items-center",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(tt,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("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:ac(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(pt,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:o,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const kb=Object.freeze(Object.defineProperty({__proto__:null,default:Nb,loader:wb,meta:vb},Symbol.toStringTag,{value:"Module"}));function Eb({request:e,context:t}){const r=t.dbNotifier||it;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(o){const a=new TextEncoder;o.enqueue(a.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
300
|
+
|
|
301
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(p);try{o.close()}catch{}}},c=u=>{try{o.enqueue(a.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
302
|
+
|
|
303
|
+
`))}catch{l()}};r.on("change",c);const p=setInterval(()=>{try{o.enqueue(a.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
304
|
+
|
|
305
|
+
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Ab=Object.freeze(Object.defineProperty({__proto__:null,loader:Eb},Symbol.toStringTag,{value:"Module"}));function Pb(){return new Response(JSON.stringify({status:"ok",version:bo,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const _b=Object.freeze(Object.defineProperty({__proto__:null,loader:Pb},Symbol.toStringTag,{value:"Module"}));function Fo(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],o=r[2],a={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?a.paths=i[1].split(`
|
|
306
|
+
`).filter(p=>p.trim().startsWith("-")).map(p=>p.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(a.paths=l[1].split(",").map(p=>p.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(a.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:a,body:o}}async function os(e,t=""){const r=[];try{const s=await we.readdir(e,{withFileTypes:!0});for(const o of s){const a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){const i=await os(ee.join(e,o.name),a);r.push(...i)}else o.isFile()&&o.name.endsWith(".md")&&r.push(a)}}catch{}return r}async function Zn(e){const t=await os(e),r=[];for(const s of t){const o=ee.join(e,s);try{const a=await we.readFile(o,"utf-8"),{frontmatter:i,body:l}=Fo(a);r.push({filePath:s,absolutePath:o,frontmatter:i,body:l})}catch{}}return r}function ic(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function lc(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Ls(e,s,{matchBase:!0}));const r=ic(t);return r?Ls(e,r,{matchBase:!0}):!1}function jb(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!ic(e)?[]:t.filter(r=>lc(r,e))}const Mb=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function zo(e){const t=[];async function r(s,o){try{const a=await ve.readdir(s,{withFileTypes:!0});for(const i of a){const l=F.join(s,i.name),c=o?`${o}/${i.name}`:i.name;i.isDirectory()&&Mb.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const Tb="codeyam-rule-state.json",Ms=1;function cc(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return qn.createHash("sha256").update(t).digest("hex")}function dc(e){return ee.join(e,".claude",Tb)}async function uc(e){const t=dc(e);try{const r=await we.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Ms?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Ms,rules:{}}):s}catch{return{version:Ms,rules:{}}}}async function pc(e,t){const r=dc(e),s=ee.dirname(r);await we.mkdir(s,{recursive:!0}),await we.writeFile(r,JSON.stringify(t,null,2)+`
|
|
307
|
+
`,"utf-8")}async function Bo(e,t){const r=await uc(e),s=new Set(t.map(o=>o.filePath));for(const o of Object.keys(r.rules))s.has(o)||delete r.rules[o];for(const o of t){const a=await we.readFile(o.absolutePath,"utf-8"),i=cc(a),l=r.rules[o.filePath];l?l.contentHash!==i&&(r.rules[o.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[o.filePath]={contentHash:i,reviewed:!1}}return await pc(e,r),r}async function ai(e,t,r,s){const o=await uc(e);if(r){const a=ee.join(e,".claude","rules"),i=ee.join(a,t),l=await we.readFile(i,"utf-8"),c=cc(l);o.rules[t]?(o.rules[t].reviewed=!0,o.rules[t].contentHash=c):o.rules[t]={contentHash:c,reviewed:!0}}else o.rules[t]&&(o.rules[t].reviewed=!1);await pc(e,o)}function Yo(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function mc(e,t=""){const r=[],s=await we.readdir(e,{withFileTypes:!0});for(const o of s){const a=t?`${t}/${o.name}`:o.name;o.isDirectory()?r.push(...await mc(ee.join(e,o.name),a)):o.name.endsWith(".md")&&r.push(a)}return r}function Tr(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 $b({request:e}){const t=pe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),o=ee.join(t,".claude","rules");if(s==="recent-changes")return Ib(t,o);if(s==="reviewed-status")return Ob(t,o);if(s==="audit")return Lb(t,o);if(s==="source-files")return Fb(t);if(s==="rule-coverage")return zb(t,o);if(s==="rule-diff"){const a=r.searchParams.get("filePath");return a?Db(t,a):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const a=r.searchParams.get("path");return a?Bb(o,a):Response.json({error:"Missing required parameter: path"},{status:400})}try{const a=await os(o),i=[];for(const u of a){const m=ee.join(o,u);try{const h=await we.readFile(m,"utf-8"),f=await we.stat(m),{frontmatter:y,body:g}=Fo(h);i.push({filePath:u,content:h,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,m)=>new Date(m.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await we.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await Zn(o),p={};if(c.length>0){const u=await Bo(t,c);for(const m of c)p[m.filePath]=Yo(u,m.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:p})}catch(a){return console.error("[API] Error loading memories:",a),Response.json({error:"Failed to load memories",details:a instanceof Error?a.message:String(a),memoryInitialized:!1},{status:500})}}async function Rb(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const o of s.split(`
|
|
309
|
+
`).filter(Boolean)){const a=o.substring(0,2);let i=o.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=a[0],c=a[1];let p=[i];if(i.endsWith("/")&&l==="?"){const u=ee.join(e,i);try{p=(await mc(u)).map(h=>i+h)}catch{continue}}for(const u of p){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let h="modified";l==="A"||l==="?"?h="added":l==="D"||c==="D"?h="deleted":(l==="M"||c==="M")&&(h="modified");let f="";try{if(h==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(h==="added"&&l==="?"){const y=`${e}/${u}`;try{const g=await we.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)"}h==="modified"&&Tr(f)||r.push({filePath:m,changeType:h,diff:f})}}}catch{}return r}async function Ib(e,t){try{const{execSync:r}=await import("child_process"),s=[],o=await Zn(t),a={};if(o.length>0){const u=await Bo(e,o);for(const m of o)a[m.filePath]=Yo(u,m.filePath)}const l=(await Rb(e,r)).filter(u=>!a[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const p=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 p){const[m,h,...f]=u.split("|"),y=f.join("|");if(!m||!h)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 S=w.replace(".claude/rules/","");let E="modified";if(b==="A"?E="added":b==="D"&&(E="deleted"),a[S])continue;let k="";try{k=r(`git show ${m} --format="" -- "${w}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),k.length>5e3&&(k=k.substring(0,5e3)+`
|
|
321
|
+
... (truncated)`)}catch{k="(diff not available)"}E==="modified"&&Tr(k)||x.push({filePath:S,changeType:E,diff:k})}x.length>0&&s.push({commitHash:m.substring(0,8),date:h,message:y,files:x})}return Response.json({changes:s,reviewedStatus:a})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function Db(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,o=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),a=parseInt(o.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(Tr(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:a}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await we.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 p=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!p)return Response.json({diff:null});const[u,m,...h]=p.split("|"),f=h.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()?Tr(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:a}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function Ob(e,t){try{const r=await Zn(t),s={};if(r.length>0){const o=await Bo(e,r);for(const a of r)s[a.filePath]=Yo(o,a.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Lb(e,t){try{const r=await Zn(t),s=await zo(e),o=[];for(const a of s){const i=r.filter(l=>lc(a,l));if(i.length>0){const l=i.reduce((c,p)=>c+p.body.length,0);o.push({filePath:a,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.body.length})),totalTextLength:l})}}return o.sort((a,i)=>i.totalTextLength-a.totalTextLength),Response.json({topPaths:o,totalFilesWithCoverage:o.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Fb(e){try{const t=await zo(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 zb(e,t){try{const[r,s]=await Promise.all([Zn(t),zo(e)]),o={};for(const a of r)o[a.filePath]=jb(a,s).length;return Response.json({coverage:o})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Bb(e,t){try{const r=await os(e),s=[];for(const a of r){const i=ee.join(e,a);try{const l=await we.readFile(i,"utf-8"),c=await we.stat(i),{frontmatter:p,body:u}=Fo(l);p.paths&&p.paths.some(m=>Ls(t,m,{matchBase:!0}))&&s.push({filePath:a,content:l,frontmatter:p,body:u,lastModified:c.mtime.toISOString()})}catch{}}const o=s.reduce((a,i)=>a+i.body.length,0);return Response.json({rules:s,totalTextLength:o})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Yb({request:e}){const t=pe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:o,filePath:a,content:i,lastModified:l}=s;if(!a)return Response.json({error:"Missing required field: filePath"},{status:400});if(o==="mark-reviewed")return await ai(t,a,!0),console.log(`[API] Rule marked as reviewed: ${a}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:a});if(o==="mark-unreviewed")return await ai(t,a,!1),console.log(`[API] Rule marked as unreviewed: ${a}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:a});const c=ee.normalize(a);if(c.includes("..")||ee.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const p=ee.join(r,c);switch(o){case"create":case"update":return i?(await we.mkdir(ee.dirname(p),{recursive:!0}),await we.writeFile(p,i,"utf-8"),console.log(`[API] Memory ${o}d: ${a}`),Response.json({success:!0,message:`Memory ${o}d successfully`,filePath:a})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await we.unlink(p),console.log(`[API] Memory deleted: ${a}`);const u=ee.dirname(p);try{(await we.readdir(u)).length===0&&u!==r&&await we.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 Ub=Object.freeze(Object.defineProperty({__proto__:null,action:Yb,loader:$b},Symbol.toStringTag,{value:"Module"}));async function Wb({request:e,context:t}){var a;let r=t.analysisQueue;if(r||(r=await Tt()),!r)return Q({error:"Queue not initialized"},{status:500});const s=new URL(e.url),o=s.searchParams.get("queryType");if(!o)return Q({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const i=s.searchParams.get("jobId");if(!i)return Q({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((a=l.currentlyExecuting)==null?void 0:a.id)===i)return Q({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(u=>u.id===i);if(c){const u=l.jobs.indexOf(c);return Q({jobId:i,status:"queued",position:u,job:c})}const p=r.getJobResult(i);return p?Q({jobId:i,status:p.status==="error"?"failed":"completed",error:p.error}):Q({jobId:i,status:"completed"})}if(o==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async p=>{const u=[];if(p.entityShas&&p.entityShas.length>0){const m=p.entityShas.map(f=>an(f)),h=await Promise.all(m);u.push(...h.filter(f=>f!==null))}return{id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}));let c;if(i.currentlyExecuting){const p=i.currentlyExecuting,u=[];if(p.entityShas&&p.entityShas.length>0){const m=p.entityShas.map(f=>an(f)),h=await Promise.all(m);u.push(...h.filter(f=>f!==null))}c={id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}return Q({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return Q({error:"Unknown queryType"},{status:400})}async function Jb({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 Tt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),Q({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:o,...a}=s;if(console.log("[Queue API] Action:",o,"Params:",Object.keys(a)),o==="enqueue"){const{jobId:i,completion:l}=r.enqueue(a);return l.catch(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),Q({jobId:i,status:"queued"})}if(o==="resume")return r.resume(),Q({status:"resumed"});if(o==="pause")return r.pause(),Q({status:"paused"});if(o==="remove"){const{jobId:i}=a;return i?r.removeJob(i)?Q({status:"removed",jobId:i}):Q({error:"Job not found in queue"},{status:404}):Q({error:"Missing jobId parameter"},{status:400})}if(o==="clear"){const i=r.clearQueue();return Q({status:"cleared",count:i})}if(o==="reorder"){const{jobId:i,direction:l}=a;return!i||!l?Q({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?Q({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?Q({status:"reordered",jobId:i,direction:l}):Q({error:"Could not reorder job (not found or at boundary)"},{status:400})}return Q({error:"Unknown action"},{status:400})}const Hb=Object.freeze(Object.defineProperty({__proto__:null,action:Jb,loader:Wb},Symbol.toStringTag,{value:"Module"})),Vb=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Gb=We(function(){return Oe(),n(es,{children:d("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-center h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[d("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),d("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:d("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(oc,{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})]})]})})}),qb=Object.freeze(Object.defineProperty({__proto__:null,default:Gb,meta:Vb},Symbol.toStringTag,{value:"Module"})),Kb=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function Qb({request:e}){var t,r;try{const s=await Hr();if(!s)return Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let o=!1;try{const c=await Te();if(c){const{project:p}=await $e(c);o=((r=(t=p.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const a=pe()||process.cwd(),i=await Vr(a),l=ul(s.projectSlug);return Q({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:o,error:null})}catch(s){return console.error("Failed to load config:",s),Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Zb(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 Xb({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),o=t.get("groqApiKey"),a=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),c=t.get("memorySettings");let p;if(r)try{p=JSON.parse(r)}catch{return Q({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return Q({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;l&&(m=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let h;if(c)try{h=JSON.parse(c)}catch{return Q({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Hr();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const w=Zb(u[b]);return{...v,startCommand:w}}return v}))}if(!await rl({universalMocks:p,pathsToIgnore:m,webapps:f,memory:h}))return Q({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(o!==void 0||a!==void 0||i!==void 0){const x=pe()||process.cwd(),v=await Vr(x);g=o!==void 0&&o!==(v.GROQ_API_KEY||"")||a!==void 0&&a!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await mp(x,{...v,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:a||void 0,OPENAI_API_KEY:i||void 0},!0)}return Q({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),Q({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function ii(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function li({mock:e,onSave:t,onCancel:r}){const[s,o]=M(e.entityName),[a,i]=M(e.filePath),[l,c]=M(e.content);return d("div",{className:"space-y-3",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>o(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:a,onChange: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"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>c(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' }"})]}),d("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!a.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:a,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function ev(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const tv=We(function(){var Re,je,De,Le,Ee;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:o,error:a}=Ve(),i=$c(),l=Oe(),c=ht(),[p,u]=M(o?"project-metadata":"memory");gt({source:"settings-page"});const[m,h]=M((t==null?void 0:t.universalMocks)||[]),[f,y]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=M((r==null?void 0:r.GROQ_API_KEY)||""),[w,S]=M((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[E,k]=M((r==null?void 0:r.OPENAI_API_KEY)||""),[N,C]=M(!1),[A,T]=M(!1),[P,_]=M(!1),[$,I]=M(!1),[R,Y]=M(!1),[H,W]=M(!1),[B,D]=M(null),[O,j]=M(!1),[q,V]=M({}),[U,Z]=M(((Re=t==null?void 0:t.memory)==null?void 0:Re.conversationReflection)??!0),[z,L]=M(((je=t==null?void 0:t.memory)==null?void 0:je.ruleMaintenance)??!0),[J,G]=M(((De=t==null?void 0:t.memory)==null?void 0:De.promptModel)??"haiku");te(()=>{var re,ye,Se,ct;if(t){h(t.universalMocks||[]);const he=(t.pathsToIgnore||[]).join(", ");y(he),x(he);const Be={};(re=t.webapps)==null||re.forEach((Je,yt)=>{Je.startCommand&&(Be[yt]=ii(Je.startCommand))}),V(Be),Z(((ye=t.memory)==null?void 0:ye.conversationReflection)??!0),L(((Se=t.memory)==null?void 0:Se.ruleMaintenance)??!0),G(((ct=t.memory)==null?void 0:ct.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),S(r.ANTHROPIC_API_KEY||""),k(r.OPENAI_API_KEY||""))},[t,r]),te(()=>{if(i!=null&&i.success){I(!0);const re=setTimeout(()=>I(!1),3e3);return()=>clearTimeout(re)}},[i]),te(()=>{if(l.state==="idle"&&l.data&&!H){console.log("[Settings] Fetcher data:",l.data);const re=l.data;if(re.success){console.log("[Settings] Save successful, revalidating..."),I(!0),W(!0),(f!==g||re.requiresRestart)&&Y(!0),c.revalidate();const ye=setTimeout(()=>{I(!1),W(!1)},3e3);return()=>clearTimeout(ye)}}},[l.state,l.data,H,c,f,g]);const X=re=>{re.preventDefault();const ye=new FormData(re.currentTarget);ye.set("universalMocks",JSON.stringify(m)),ye.set("startCommands",JSON.stringify(q)),ye.set("memorySettings",JSON.stringify({conversationReflection:U,ruleMaintenance:z,promptModel:J})),console.log("[Settings] Submitting form data:",{universalMocks:ye.get("universalMocks"),startCommands:ye.get("startCommands"),openAiApiKey:ye.get("openAiApiKey")?"***":"(empty)"}),l.submit(ye,{method:"post"})},le=re=>{h([...m,re]),j(!1)},xe=(re,ye)=>{const Se=[...m];Se[re]=ye,h(Se),D(null)},oe=re=>{h(m.filter((ye,Se)=>Se!==re))};if(a)return d("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:a})})]});const me=[{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"}],Ce=o?me:me.filter(re=>re.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[d("div",{className:"mb-8 flex justify-between items-start",children:[d("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:l.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:l.state==="submitting"?"Saving...":"Save Settings"})]}),($||R||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&d("div",{className:"mb-4 space-y-3",children:[$&&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!"}),R&&d("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(Mt,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const re=l.data;return typeof re.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:re.error}):null}return null})()]}),d("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(re=>n("li",{children:n("button",{type:"button",onClick:()=>u(re.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${p===re.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:re.label})},re.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:X,className:"space-y-6",children:[p==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((re,ye)=>{var Se;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",d("span",{className:"text-gray-900 font-mono text-xs",children:[re.startCommand.command," ",(Se=re.startCommand.args)==null?void 0:Se.join(" ")]})]})]})},ye)})}):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`."})]})]}),p==="ai-provider"&&d("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:N?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:re=>b(re.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:()=>C(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:N?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:w,onChange:re=>S(re.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>T(!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"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:P?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:E,onChange:re=>k(re.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:()=>_(!P),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:P?"Hide":"Show"})]})]})]})]})]}),p==="commands"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((re,ye)=>d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[d("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:re.path==="."?"Root":re.path}),n("div",{className:"text-sm text-gray-600",children:re.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${ye}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ye}`,name:`startCommand-${ye}`,value:q[ye]||"",onChange:Se=>V({...q,[ye]:Se.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"})]})]},ye))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),p==="paths-to-ignore"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:re=>y(re.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),d("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),p==="universal-mocks"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),m.length===0?d("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>j(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:m.map((re,ye)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:B===ye?n(li,{mock:re,onSave:Se=>xe(ye,Se),onCancel:()=>D(null)}):n(ue,{children:d("div",{className:"flex justify-between items-start mb-2",children:[d("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:re.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:re.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:re.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>D(ye),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:()=>oe(ye),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ye))}),m.length>0&&n("button",{type:"button",onClick:()=>j(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),p==="memory"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":U,onClick:()=>Z(!U),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 ${U?"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 ${U?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":z,onClick:()=>L(!z),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 ${z?"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 ${z?"translate-x-5":"translate-x-0"}`})})]})}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(re=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${J===re.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:re.value,checked:J===re.value,onChange:()=>G(re.value),className:"mt-1 accent-[#005C75]"}),d("div",{children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:re.label}),re.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:re.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:re.description})]})]},re.value))})]})]})]}),p==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&d("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((re,ye)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:ii(re.startCommand)})]})]})},ye))})]})]}),s&&d("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Le=s.templateVersion.gitCommit)==null?void 0:Le.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",ev(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((Ee=s.cachedAnalyzerVersion.gitCommit)==null?void 0:Ee.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),O&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(li,{mock:{entityName:"",filePath:"",content:""},onSave:le,onCancel:()=>j(!1)})]})})]})})}),nv=Object.freeze(Object.defineProperty({__proto__:null,action:Xb,default:tv,loader:Qb,meta:Kb},Symbol.toStringTag,{value:"Module"}));async function rv({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=pe();if(!r)return new Response("Project root not found",{status:500});const o=ee.extname(t)!==""?t:`${t}.html`,a=ee.join(r,".codeyam","captures","static",o);try{await we.access(a);let i=await we.readFile(a);const l=ee.extname(a).toLowerCase();let c="application/octet-stream";if(l===".html"){c="text/html";let p=i.toString("utf-8");const u=p.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const h=u[1].match(/=\s*(\{[\s\S]*\})/);if(h){const f=JSON.parse(h[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;p=p.replace(u[0],y)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(p,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const sv=Object.freeze(Object.defineProperty({__proto__:null,loader:rv},Symbol.toStringTag,{value:"Module"}));function ov(e,t,r=10){var c;const s=new Map,o=p=>p.entityType==="visual"||p.entityType==="library";for(const p of e)o(p)&&s.set(p.sha,{entity:p,depth:0});const a=new Map;for(const p of t){const u=(c=p.metadata)==null?void 0:c.importedBy;if(u)for(const m of Object.keys(u))for(const h of Object.keys(u[m])){const{shas:f}=u[m][h];for(const y of f)a.has(p.sha)||a.set(p.sha,new Set),a.get(p.sha).add(y)}}const i=[],l=new Set;for(const p of e)i.push({sha:p.sha,depth:0}),l.add(p.sha);for(;i.length>0;){const{sha:p,depth:u}=i.shift();if(u>=r)continue;const m=a.get(p);if(m)for(const h of m){if(l.has(h))continue;l.add(h);const f=t.find(y=>y.sha===h);if(f){if(o(f)){const y=u+1,g=s.get(h);(!g||y<g.depth)&&s.set(h,{entity:f,depth:y})}i.push({sha:h,depth:u+1})}}}return Array.from(s.values()).sort((p,u)=>p.depth!==u.depth?p.depth-u.depth:p.entity.name.localeCompare(u.entity.name))}function $r(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const o=s.sort((a,i)=>{var p,u;const l=((p=a.metadata)==null?void 0:p.editedAt)||a.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(o[0])}return r}function hc(e,t){const r=new Map,s=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&s.add(o.oldPath);for(const o of e){const a=t.filter(c=>c.filePath===o.path||o.status==="renamed"&&o.oldPath&&c.filePath===o.oldPath),i=a.filter(c=>{var p,u;return s.has(c.filePath)&&((p=c.metadata)==null?void 0:p.isUncommitted)&&!((u=c.metadata)!=null&&u.isSuperseded)}),l=$r(i);r.set(o.path,{status:o,entities:a,editedEntities:l})}return r}function av(e,t,r){const s=new Map;if(!r){for(const a of e)if(a.status==="deleted")s.set(a.path,{status:a,entities:[]});else{const i=t.filter(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),l=$r(i);s.set(a.path,{status:a,entities:l})}return s}const o=new Map;for(const a of r.fileComparisons){const i=new Set;for(const l of a.newEntities)i.add(l.name);for(const l of a.modifiedEntities)i.add(l.name);for(const l of a.deletedEntities)i.add(l.name);i.size>0&&o.set(a.filePath,i)}for(const a of e){const i=o.get(a.path);if(a.status==="deleted")s.set(a.path,{status:a,entities:[]});else{const l=i?t.filter(p=>(p.filePath===a.path||a.status==="renamed"&&a.oldPath&&p.filePath===a.oldPath)&&i.has(p.name)):[],c=$r(l);s.set(a.path,{status:a,entities:c})}}return s}function iv(e,t){const r=new Map,s=fc(e,t);for(const o of s){const i=ov([o],t).filter(({depth:l})=>l>0);r.set(o.sha,i)}return r}function fc(e,t){const r=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&r.add(o.oldPath);const s=t.filter(o=>{var a,i;return r.has(o.filePath)&&((a=o.metadata)==null?void 0:a.isUncommitted)&&!((i=o.metadata)!=null&&i.isSuperseded)});return $r(s)}function lv({recentSimulations:e}){const t=ne(()=>{const r=new Map;return e.forEach(s=>{const o=s.entitySha,a=r.get(o);a?a.push(s):r.set(o,[s])}),Array.from(r.entries()).map(([s,o])=>({entitySha:s,entityName:o[0].entityName,scenarios:o}))},[e]);return d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?d(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>d("div",{children:[d("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Un,{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,o)=>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:a=>{a.currentTarget.style.borderColor="#005C75",a.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="#E5E7EB",a.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(Ge,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${o}`))})]},r.entitySha))}),n(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 →"})]}):d("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Un,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),d("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(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 cv="/assets/codeyam-name-logo-CvKwUgHo.svg",dv=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function uv({request:e,context:t}){var r,s,o,a,i;try{const l=await Te();if(l){const{project:$}=await $e(l);if(((r=$.metadata)==null?void 0:r.editorMode)??!1)return ma("/editor");if(!(((o=(s=$.metadata)==null?void 0:s.labs)==null?void 0:o.simulations)??!1))return ma("/memory")}const c=t.analysisQueue,p=c?c.getState():{paused:!1,jobs:[]},[u,m]=await Promise.all([cn(),Nn()]),h=kn(),f=u?hc(h,u):new Map,y=Array.from(f.entries()).sort(($,I)=>$[0].localeCompare(I[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter($=>$.entityType==="visual").length)||0,v=(u==null?void 0:u.filter($=>$.entityType==="library").length)||0,b=u?fc(h,u):[],w=b.length,S=(u==null?void 0:u.filter($=>($.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length)||0,E=(u==null?void 0:u.reduce(($,I)=>{var Y,H,W;const R=((W=(H=(Y=I.analyses)==null?void 0:Y[0])==null?void 0:H.scenarios)==null?void 0:W.length)||0;return $+R},0))||0,k=(u==null?void 0:u.reduce(($,I)=>{var H,W;const Y=(((W=(H=I.analyses)==null?void 0:H[0])==null?void 0:W.scenarios)||[]).filter(B=>{var D,O;return(O=(D=B.metadata)==null?void 0:D.screenshotPaths)==null?void 0:O[0]}).length;return $+Y},0))||0,N=[];u==null||u.forEach($=>{var R;const I=(R=$.analyses)==null?void 0:R[0];I!=null&&I.scenarios&&I.scenarios.filter(H=>{var W;return!((W=H.metadata)!=null&&W.sameAsDefault)}).forEach(H=>{var B,D;const W=(D=(B=H.metadata)==null?void 0:B.screenshotPaths)==null?void 0:D[0];W&&N.push({entitySha:$.sha,entityName:$.name,scenarioId:H.id,scenarioName:H.name,screenshotPath:W,createdAt:I.createdAt||""})})}),N.sort(($,I)=>new Date(I.createdAt).getTime()-new Date($.createdAt).getTime());const C=N.slice(0,16),A=(u==null?void 0:u.filter($=>$.entityType==="visual").filter($=>{var Y,H;const I=(Y=$.analyses)==null?void 0:Y[0];return!((H=I==null?void 0:I.scenarios)==null?void 0:H.some(W=>{var B,D;return(D=(B=W.metadata)==null?void 0:B.screenshotPaths)==null?void 0:D[0]}))}).slice(0,8))||[],T=(a=m==null?void 0:m.metadata)==null?void 0:a.currentRun,P=((i=T==null?void 0:T.currentEntityShas)==null?void 0:i.length)||0,_=p.jobs.length||0;return Q({stats:{totalEntities:g,visualEntities:x,libraryEntities:v,uncommittedEntities:w,entitiesWithAnalyses:S,totalScenarios:E,capturedScreenshots:k,currentlyAnalyzing:P,filesOnQueue:_},uncommittedFiles:y,uncommittedEntitiesList:b,recentSimulations:C,visualEntitiesForSimulation:A,projectSlug:l,queueState:p,currentCommit:m})}catch(l){return console.error("Failed to load dashboard data:",l),Q({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 pv=We(function(){var B,D;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:o,visualEntitiesForSimulation:a,projectSlug:i,queueState:l,currentCommit:c}=Ve(),p=Oe(),u=ht(),{showToast:m}=ho();gt({source:"dashboard"});const[h,f]=M(new Set),[y,g]=M(null),[x,v]=M(!1),[b,w]=M(!1),{lastLine:S,isCompleted:E}=Pt(i,!!y),{simulatingEntity:k,scenarios:N,scenarioStatuses:C,allScenariosCaptured:A}=ne(()=>{var L,J;const O={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return O;const j=a==null?void 0:a.find(G=>G.sha===y);if(!j)return O;const q=(L=j.analyses)==null?void 0:L[0],V=(q==null?void 0:q.scenarios)||[],U=((J=q==null?void 0:q.status)==null?void 0:J.scenarios)||[],Z=U.filter(G=>G.screenshotFinishedAt).length,z=V.length>0&&Z===V.length;return{simulatingEntity:j,scenarios:V,scenarioStatuses:U,allScenariosCaptured:z}},[y,a]);te(()=>{(E||A)&&g(null)},[E,A]);const T=(B=c==null?void 0:c.metadata)==null?void 0:B.currentRun,P=new Set((T==null?void 0:T.currentEntityShas)||[]),_=new Set(l.jobs.flatMap(O=>O.entityShas||[])),$=new Set(((D=l.currentlyExecuting)==null?void 0:D.entityShas)||[]),I=s.filter(O=>O.entityType==="visual"||O.entityType==="library"),R=I.filter(O=>!P.has(O.sha)&&!_.has(O.sha)&&!$.has(O.sha)),Y=()=>{if(R.length===0){m("All entities are already queued or analyzing","info",3e3);return}const O=R.map(j=>j.sha);w(!0),m(`Starting analysis for ${R.length} entities...`,"info",3e3),p.submit({entityShas:O.join(",")},{method:"post",action:"/api/analyze"})};te(()=>{if(p.state==="idle"&&p.data){const O=p.data;O.success?(console.log("[Analyze All] Success:",O.message),m(`Analysis started for ${O.entityCount} entities in ${O.fileCount} files. Watch the logs for progress.`,"success",6e3),w(!1)):O.error&&(console.error("[Analyze All] Error:",O.error),m(`Error: ${O.error}`,"error",8e3),w(!1))}},[p.state,p.data,m]);const H=O=>{f(j=>{const q=new Set(j);return q.has(O)?q.delete(O):q.add(O),q})},W=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12",children:[d("header",{className:"mb-8 flex justify-between items-center",children:[d("div",{className:"flex items-center gap-4",children:[n("img",{src:cv,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,O=>O.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:W.map((O,j)=>n(de,{to:O.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 ${O.color}`},children:d("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[d("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[d("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:O.label}),d("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[O.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:O.color},children:"View All →"})]}),d("div",{className:"flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-3",children:[d("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${O.color}15`},children:[O.iconType==="folder"&&n(id,{size:20,style:{color:O.color}}),O.iconType==="check"&&n(so,{size:20,style:{color:O.color}}),O.iconType==="image"&&n(Un,{size:20,style:{color:O.color}}),O.iconType==="code-xml"&&n(ld,{size:20,style:{color:O.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:O.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:O.color},children:"View All →"})]})]})},j))}),d("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[d("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[d("div",{className:"flex justify-between items-start mb-5",children:[d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),I.length>0&&n("button",{onClick:Y,disabled:p.state!=="idle"||b||R.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:O=>O.currentTarget.style.backgroundColor="#004560",onMouseLeave:O=>O.currentTarget.style.backgroundColor="#005C75",children:p.state!=="idle"||b?"Starting analysis...":R.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([O,j])=>{const q=h.has(O),V=j.editedEntities||[];return d("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>H(O),role:"button",tabIndex:0,children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:q?"▼":"▶"}),d("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[d("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),d("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:O}),d("span",{className:"text-xs text-gray-500",children:[V.length," entit",V.length!==1?"ies":"y"]})]})]})}),q&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:V.length>0?V.map(U=>{const Z=P.has(U.sha),z=_.has(U.sha)||$.has(U.sha);return d(de,{to:`/entity/${U.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:L=>L.currentTarget.style.borderColor="#005C75",onMouseLeave:L=>L.currentTarget.style.borderColor="inherit",children:[d("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:U.entityType==="visual"?"#8B5CF615":U.entityType==="library"?"#6366F1":"#EC4899"},children:[U.entityType==="visual"&&n(Un,{size:16,style:{color:"#8B5CF6"}}),U.entityType==="library"&&n(Ai,{size:16,className:"text-white"}),U.entityType==="other"&&n(cd,{size:16,className:"text-white"})]}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:U.name}),U.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),U.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),U.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),U.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:U.description})]}),d("div",{className:"flex items-center gap-2 shrink-0",children:[Z&&d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(pt,{size:14,className:"animate-spin"}),"Analyzing..."]}),!Z&&z&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!Z&&!z&&n("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),m(`Starting analysis for ${U.name}...`,"info",3e3),p.submit({entityShas:U.sha},{method:"post",action:"/api/analyze"})},disabled:p.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:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},U.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},O)})}):d("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:d("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(lv,{recentSimulations:o}),y&&d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:o.length>0?`Latest ${o.length} captured screenshot${o.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&d("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[k&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(tt,{type:"visual"})}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",k.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:k.filePath})]})]})}),A?d("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),d("span",{children:["Complete (",N.length," scenario",N.length!==1?"s":"",")"]})]}):S?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(pt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:S,children:S}),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"})]}):p.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(pt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(pt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),N.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:N.slice(0,8).map((O,j)=>{var J,G,X;const q=(J=k==null?void 0:k.analyses)==null?void 0:J[0],V=ss(O,q==null?void 0:q.status,void 0,y||void 0,void 0),U=(X=(G=O.metadata)==null?void 0:G.screenshotPaths)==null?void 0:X[0],Z=V.isCaptured,z=V.status==="capturing"||V.status==="starting",L=V.hasError;return Z?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(Ge,{screenshotPath:U,alt:O.name,title:O.name,className:"max-w-full max-h-full object-contain object-center"})},j):L?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:V.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},j):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:`${z?"Capturing":"Pending"} ${O.name}...`,children:n("span",{className:z?"animate-pulse":"text-gray-400",children:z?"⋯":"⏹️"})},j)})})]})]})]}),x&&i&&n(Ft,{projectSlug:i,onClose:()=>v(!1)})]})})}),mv=Object.freeze(Object.defineProperty({__proto__:null,default:pv,loader:uv,meta:dv},Symbol.toStringTag,{value:"Module"}));function Uo(e){const[t,r]=M(null),[s,o]=M(!1),a=ae(()=>{e&&(o(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),o(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),o(!1)}))},[e]);return te(()=>{e&&a()},[e,a]),{results:t,isRunning:s,runTests:a}}function In({imgSrc:e,name:t,isActive:r,onSelect:s}){return d("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 Ts({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:o}=Uo(e);if(s&&!r)return d("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!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 a=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=a.length>0?a:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("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:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:m,children:m.split(`
|
|
333
|
+
`)[0]},h)))]},c.fullName)}),n("button",{onClick:o,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 Xt({filePath:e}){return e?d("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(Mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function hv({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:o,onZoomChange:a,analyzedEntities:i=[],glossaryFunctions:l=[],activeAnalyzedScenarioId:c,onAnalyzedScenarioSelect:p,entityImports:u,pageFilePaths:m={}}){const{pageGroups:h,componentGroups:f}=ne(()=>{var A;const k=new Map,N=new Map;for(const T of e)if(T.componentName){const P=N.get(T.componentName)||[];P.push(T),N.set(T.componentName,P)}else if(_o(T.url)){const P=(A=T.url)==null?void 0:A.match(/[?&]c=([^&]+)/),_=P?decodeURIComponent(P[1]):"Isolated",$=N.get(_)||[];$.push(T),N.set(_,$)}else{const P=nt(T.url),_=k.get(P)||[];_.push(T),k.set(P,_)}const C=new Map([...N.entries()].sort(([T],[P])=>T.localeCompare(P)));return{pageGroups:k,componentGroups:C}},[e]),y=ne(()=>{const k=new Set((i||[]).filter(C=>C.entityType==="visual").map(C=>C.name)),N=new Map;for(const[C,A]of f)k.has(C)||N.set(C,A);return N},[f,i]),{visualEntities:g,libraryEntities:x}=ne(()=>{const k=i.filter(C=>C.entityType==="visual").sort((C,A)=>C.name.localeCompare(A.name)),N=i.filter(C=>C.entityType==="library"||C.entityType==="functionCall").sort((C,A)=>C.name.localeCompare(A.name));return{visualEntities:k,libraryEntities:N}},[i]),v=ne(()=>{const k=new Set(x.map(N=>N.name));return l.filter(N=>!k.has(N.name)).sort((N,C)=>N.name.localeCompare(C.name))},[l,x]),b=i.some(k=>k.isAnalyzing),w=be(null),S=be(0),E=ae(()=>{w.current&&(S.current=w.current.scrollTop)},[]);if(te(()=>{w.current&&S.current>0&&(w.current.scrollTop=S.current)}),e.length===0&&i.length===0&&v.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(o){const k=f.get(o)||[],N=new Set((u==null?void 0:u[o])||[]),C=N.size>0,A=C?g.filter(P=>N.has(P.name)):[],T=C?x.filter(P=>N.has(P.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("button",{onClick:()=>a(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:o})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:k.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):k.map(P=>n(In,{imgSrc:P.screenshotPath?`/api/editor-scenario-image/${P.id}.png`:null,name:P.name,isActive:P.id===r,onSelect:()=>s(P)},P.id))}),A.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),A.map(P=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>a(P.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:P.name})}),n(Xt,{filePath:P.filePath,projectRoot:t}),(P.scenarios.length>0||P.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:P.scenarios.map(_=>n(In,{imgSrc:_.screenshotPath?`/api/screenshot/${_.screenshotPath}`:null,name:_.name,isActive:_.id===c,onSelect:()=>p==null?void 0:p({analysisId:P.analysisId,scenarioId:_.id,scenarioName:_.name,entitySha:P.sha,entityName:P.name})},_.id))})]},P.sha))]}),T.length>0&&d("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),T.map(P=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:P.name})}),n(Xt,{filePath:P.filePath,projectRoot:t}),P.testFile&&n(Ts,{testFile:P.testFile,entityName:P.name})]},P.sha))]})]})})}return n("div",{ref:w,onScroll:E,className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-3",children:[h.size>0&&d("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),[...h.entries()].sort(([k],[N])=>k==="Home"?-1:N==="Home"?1:k.localeCompare(N)).map(([k,N])=>d("div",{className:"px-2 pt-1",children:[n("div",{className:"py-0.5",children:n("span",{className:"text-[11px] font-medium text-gray-400",children:k})}),m[k]&&n(Xt,{filePath:m[k],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:N.map(C=>n(In,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===r&&!c,onSelect:()=>s(C)},C.id))})]},k))]}),y.size>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([k,N])=>{var C;return d("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>a(k),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k})}),((C=N[0])==null?void 0:C.componentPath)&&n(Xt,{filePath:N[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:N.map(A=>n(In,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===r&&!c,onSelect:()=>s(A)},A.id))})]},k)})]}),g.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),b&&e.length===0&&i.every(k=>k.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),g.map(k=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>a(k.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k.name}),k.isAnalyzing&&k.scenarioCount===0&&d("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Xt,{filePath:k.filePath,projectRoot:t}),(k.scenarios.length>0||k.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[k.scenarios.map(N=>n(In,{imgSrc:N.screenshotPath?`/api/screenshot/${N.screenshotPath}`:null,name:N.name,isActive:N.id===c,onSelect:()=>p==null?void 0:p({analysisId:k.analysisId,scenarioId:N.id,scenarioName:N.name,entitySha:k.sha,entityName:k.name})},N.id)),k.pendingScenarios.map(N=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:N,children:N},N))]})]},k.sha))]}),(x.length>0||v.length>0)&&d("div",{className:`pt-2 mt-1 ${g.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"})}),x.map(k=>d("div",{className:"mt-2",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:k.name}),k.isAnalyzing&&k.scenarioCount===0&&d("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Xt,{filePath:k.filePath,projectRoot:t}),k.testFile?n(Ts,{testFile:k.testFile,entityName:k.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},k.sha)),v.map(k=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:k.name})}),n(Xt,{filePath:k.filePath,projectRoot:t}),n(Ts,{testFile:k.testFile,entityName:k.name})]},k.name))]})]})})}const ci=120;function gc({text:e,theme:t}){const[r,s]=M(!1),o=e.length>ci,a=o&&!r?e.slice(0,ci)+"…":e,i=t==="light";return d("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),d("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[a,o&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}function di({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function fv({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:o}=Uo(e);if(s&&!r)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const a=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=a.length>0?a:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("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:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:m,children:m.split(`
|
|
334
|
+
`)[0]},h)))]},c.fullName)}),n("button",{onClick:o,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}const gv={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function yv({files:e}){return d("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[d("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",e.length,")"]}),n("div",{className:"mt-1 space-y-0.5 max-h-[150px] overflow-auto",children:e.map(t=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${gv[t.status]||"text-gray-500"}`,children:t.status==="added"||t.status==="untracked"?"A":t.status==="modified"?"M":t.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-400 truncate font-mono",children:t.path})]},t.path))})]})}const xv={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 bv(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function vv(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const wv=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function Nv({entries:e,onScreenshotClick:t}){const[r,s]=M(!1),[o,a]=M("7d"),i=ne(()=>bg(e,o),[e,o]);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>s(!r),className:"w-full flex items-center justify-between px-3 py-2.5 cursor-pointer bg-transparent border-none text-left hover:bg-[#333] transition-colors",children:[n("span",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Timeframe Summary"}),n("span",{className:`text-gray-500 text-[10px] transition-transform ${r?"rotate-180":""}`,children:"▼"})]}),r&&d("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:wv.map(l=>n("button",{onClick:()=>a(l.value),className:`px-2.5 py-1 text-[10px] font-medium rounded transition-colors cursor-pointer border ${o===l.value?"bg-[#005c75] text-white border-[#005c75]":"bg-transparent text-gray-400 border-[#4d4d4d] hover:text-white hover:border-[#005c75]"}`,children:l.label},l.value))}),d("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[d("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.totalScenarios})," ",i.totalScenarios===1?"scenario changed":"scenarios changed"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.entryCount})," ",i.entryCount===1?"entry":"entries"]})]}),i.totalScenarios===0?n("p",{className:"text-[11px] text-gray-500 italic m-0",children:"No scenario changes in this period."}):d("div",{className:"space-y-3",children:[i.appScenarios.length>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),i.appScenarios.map(l=>n(ui,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(p=>n(ui,{scenario:p,onScreenshotClick:t},p.name))]},l))]})]})]})]})}function ui({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return d("div",{className:"pl-2",children:[n("span",{className:"text-[10px] text-gray-500 block mb-1",children:s}),n("div",{className:"flex items-center gap-1 overflow-x-auto",children:e.screenshots.map((o,a)=>d("div",{className:"flex items-center shrink-0",children:[a>0&&n("span",{className:"text-[8px] text-gray-600 mx-0.5",children:"→"}),n("button",{type:"button",className:"w-16 h-16 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",title:`${e.name} (${new Date(o.time).toLocaleDateString()})`,onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${o.path.replace("screenshots/","")}`,commitSha:null,commitMessage:null,scenarioName:e.name}),children:n("img",{src:`/api/editor-journal-image/${o.path.replace("screenshots/","")}`,alt:e.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})})]},o.path))})]})}function Cv({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[]}){const[s,o]=M([]),[a,i]=M(!0),[l,c]=M(new Set),p=ae(h=>{c(f=>{const y=new Set(f);return y.has(h)?y.delete(h):y.add(h),y})},[]),u=ae(async()=>{try{const h=await fetch("/api/editor-journal");if(h.ok){const f=await h.json();o(f.entries||[])}}catch{}finally{i(!1)}},[]);if(te(()=>{u()},[u]),te(()=>{e&&u()},[e,u]),te(()=>{const h=new EventSource("/api/events");return h.addEventListener("message",f=>{try{const y=JSON.parse(f.data);y.type==="db-change"&&y.changeType==="journal"&&u()}catch{}}),()=>h.close()},[u]),a)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(s.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const m=vg(s);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(Nv,{entries:s,onScreenshotClick:t}),[...m.entries()].map(([h,f])=>d("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:vv(h)})}),n("div",{className:"space-y-2",children:f.map((y,g)=>{const x=xv[y.type]||{label:y.type,color:"bg-gray-600"},v=`${y.time}-${g}`,b=l.has(v);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${b?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>p(v),children:d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:y.title}),n("span",{className:`${x.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:x.label})]}),n("span",{className:"text-[10px] text-gray-500",children:bv(y.time)}),y.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:y.featureName,children:y.featureName})]})}),y.userPrompt&&n(gc,{text:y.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:y.description}),y.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,commitSha:y.commitSha,commitMessage:y.commitMessage,scenarioName:y.title}),children:n("img",{src:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,alt:y.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),y.scenarioScreenshots&&y.scenarioScreenshots.length>0&&(()=>{const w=wg(y.scenarioScreenshots),S=y.entityChangeStatus,E=w.filter(([T])=>T==="App").flatMap(([,T])=>T),k=w.filter(([T])=>T!=="App"),N=new Map;for(const T of E){const P=nt(T.url??null),_=N.get(P)||[];_.push(T),N.set(P,_)}const C=[...N.entries()],A=T=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${T.path.replace("screenshots/","")}`,commitSha:y.commitSha,commitMessage:y.commitMessage,scenarioName:T.name}),children:n("img",{src:`/api/editor-journal-image/${T.path.replace("screenshots/","")}`,alt:T.name,title:T.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},T.path);return d("div",{className:"space-y-2",children:[C.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),C.map(([T,P])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:T}),(S==null?void 0:S[T])&&n(di,{status:S[T]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.map(A)})]},T))]}),k.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),k.map(([T,P])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:T}),(S==null?void 0:S[T])&&n(di,{status:S[T]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.map(A)})]},T))]})]})})(),r.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(w=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:w.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:w.filePath}),w.testFile?n(fv,{testFile:w.testFile,entityName:w.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.name))})]}),y.commitSha&&d("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:y.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:y.commitMessage})]}),b&&y.modifiedFiles&&y.modifiedFiles.length>0&&n(yv,{files:y.modifiedFiles})]}),d("button",{onClick:()=>p(v),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",b?"Collapse":"Expand"," ———"]})]},v)})})]},h))]})})}function Dn({imgSrc:e,name:t,isActive:r,onSelect:s}){return d("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:t,children:[n("div",{className:`w-full aspect-square 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-full ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function hr({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(Mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Sv({hasProject:e,scenarios:t,analyzedEntities:r,glossaryFunctions:s=[],projectRoot:o,activeScenarioId:a,onScenarioSelect:i,onAnalyzedScenarioSelect:l,onSwitchToBuild:c,zoomComponent:p,onZoomChange:u,entityImports:m,pageFilePaths:h={},projectTitle:f,projectDescription:y}){const{pageGroups:g,componentGroups:x}=ne(()=>{var T;const N=new Map,C=new Map;for(const P of t)if(P.componentName){const _=C.get(P.componentName)||[];_.push(P),C.set(P.componentName,_)}else if(_o(P.url)){const _=(T=P.url)==null?void 0:T.match(/[?&]c=([^&]+)/),$=_?decodeURIComponent(_[1]):"Isolated",I=C.get($)||[];I.push(P),C.set($,I)}else{const _=nt(P.url),$=N.get(_)||[];$.push(P),N.set(_,$)}const A=new Map([...C.entries()].sort(([P],[_])=>P.localeCompare(_)));return{pageGroups:N,componentGroups:A}},[t]),v=ne(()=>r.filter(N=>N.entityType==="visual").sort((N,C)=>N.name.localeCompare(C.name)),[r]),b=ne(()=>{const N=new Map;for(const C of s)N.set(C.name,C);return N},[s]),w=be(null),S=be(0),E=ae(()=>{w.current&&(S.current=w.current.scrollTop)},[]);if(te(()=>{w.current&&S.current>0&&(w.current.scrollTop=S.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:d("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:c,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(!(t.length>0||v.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[f?d(ue,{children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:f}),y&&n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:y})]}):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",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:c,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(p){const N=g.get(p)||[],C=x.get(p)||[],A=v.find(D=>D.name===p),T=b.get(p),P=[...N,...C],_=new Set((m==null?void 0:m[p])||[]),$=_.size>0,I=$?[...x.entries()].filter(([D])=>_.has(D)):[],R=$?v.filter(D=>_.has(D.name)&&!I.some(([O])=>O===D.name)):[],Y=$?s.filter(D=>_.has(D.name)):[],H=I.length>0||R.length>0,W=Y.length>0,B=H||W;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[d("button",{onClick:()=>u(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"]}),d("div",{children:[n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:p}),T&&n(hr,{filePath:T.filePath,projectRoot:o})]}),P.length>0&&n("div",{className:"flex flex-wrap gap-2",children:P.map(D=>n(Dn,{imgSrc:D.screenshotPath?`/api/editor-scenario-image/${D.id}.png`:null,name:D.name,isActive:D.id===a,onSelect:()=>i(D)},D.id))}),A&&(A.scenarios.length>0||A.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2",children:[A.scenarios.map(D=>n(Dn,{imgSrc:D.screenshotPath?`/api/screenshot/${D.screenshotPath}`:null,name:D.name,isActive:!1,onSelect:()=>l({analysisId:A.analysisId,scenarioId:D.id,scenarioName:D.name,entitySha:A.sha,entityName:A.name})},D.id)),A.pendingScenarios.map(D=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:D,children:D},D))]}),T&&d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(hr,{filePath:T.testFile,projectRoot:o})]}),P.length===0&&!A&&!T&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"}),B&&d("div",{className:"pt-3 mt-2 border-t border-[#3d3d3d] space-y-3",children:[H&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),I.map(([D,O])=>d("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(D),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:D})}),O.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:O.map(j=>n(Dn,{imgSrc:j.screenshotPath?`/api/editor-scenario-image/${j.id}.png`:null,name:j.name,isActive:j.id===a,onSelect:()=>i(j)},j.id))})]},D)),R.map(D=>d("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(D.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:D.name})}),(D.scenarios.length>0||D.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[D.scenarios.map(O=>n(Dn,{imgSrc:O.screenshotPath?`/api/screenshot/${O.screenshotPath}`:null,name:O.name,isActive:!1,onSelect:()=>l({analysisId:D.analysisId,scenarioId:O.id,scenarioName:O.name,entitySha:D.sha,entityName:D.name})},O.id)),D.pendingScenarios.map(O=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:O,children:O},O))]})]},D.sha))]}),W&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),Y.map(D=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(D.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:D.name})}),n(hr,{filePath:D.filePath,projectRoot:o}),D.testFile&&d("div",{className:"flex items-center gap-1.5 mt-0.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:D.testFile})]})]},D.name))]})]})]})})}return n("div",{ref:w,onScroll:E,className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-4",children:[f&&d("div",{children:[n("h2",{className:"text-base font-semibold text-white m-0 font-['IBM_Plex_Sans']",children:f}),y&&n("p",{className:"text-xs text-gray-400 m-0 mt-1 font-['IBM_Plex_Sans'] leading-relaxed",children:y})]}),g.size>0&&d("div",{children:[d("div",{className:"flex items-center justify-between",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),n("button",{onClick:c,className:"px-2.5 py-1 text-[10px] font-medium text-gray-400 bg-[#2a2a2a] border border-[#4d4d4d] rounded hover:bg-[#333] hover:text-white hover:border-[#005c75] transition-colors cursor-pointer",children:"+ New Page"})]}),d("p",{className:"text-[11px] text-gray-500 m-0 mt-1.5 font-['IBM_Plex_Sans'] leading-relaxed",children:["Select a page scenario below and switch to"," ",n("button",{onClick:c,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"Build"})," ","to change or enhance an existing page or"," ",n("button",{onClick:c,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"create a new page"})]}),[...g.entries()].sort(([N],[C])=>N==="Home"?-1:C==="Home"?1:N.localeCompare(C)).map(([N,C])=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(N),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:N})}),h[N]&&n(hr,{filePath:h[N],projectRoot:o}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:C.map(A=>n(Dn,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===a,onSelect:()=>i(A)},A.id))})]},N))]})]})})}const pi={new:0,edited:1,impacted:2};function mi({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function hi({filePath:e}){const[t,r]=M(null),[s,o]=M(!0),[a,i]=M(null);return te(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),te(()=>{o(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>o(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!a?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(a,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function fi({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?d(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?d(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function gi({scenarioId:e,name:t,isActive:r,onSelect:s}){const[o,a]=M(!1);return te(()=>{a(!1)},[e]),d("button",{onClick:s,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all ${r?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:o?n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center",children:n("span",{className:"text-[9px] text-gray-400",children:"No preview"})}):n("img",{src:`/api/editor-scenario-image/${e}.png`,alt:t,className:"w-full h-full object-contain bg-white",loading:"lazy",onError:()=>a(!0)})}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${r?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:t})]})}function kv({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(Mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Ev({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:o}=Uo(e);if(s&&!r)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:r.errorMessage})});const a=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=a.length>0?a:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):c.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${c.status==="passed"?"text-green-600":c.status==="failed"?"text-red-500":"text-gray-400"}`,children:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:m,children:m.split(`
|
|
335
|
+
`)[0]},h)))]},c.fullName)}),n("button",{onClick:o,disabled:s,className:"mt-1 text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function yi(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function xi(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,c;const o=((l=t[r])==null?void 0:l.status)||"impacted",a=((c=t[s])==null?void 0:c.status)||"impacted",i=(pi[o]??2)-(pi[a]??2);return i!==0?i:r.localeCompare(s)})}function Av({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],projectRoot:s,activeScenarioId:o,onScenarioSelect:a,onClose:i,entityChangeStatus:l={},modifiedFiles:c=[],featureName:p,userPrompt:u}){const m=ne(()=>{if(t.length===0||Object.keys(l).length===0)return e;const N=new Set(e.map(A=>A.id)),C=t.filter(A=>{var P;if(N.has(A.id))return!1;const T=A.componentName||nt(A.url);return((P=l[T])==null?void 0:P.status)==="impacted"});return C.length===0?e:[...e,...C]},[e,t,l]),h=ne(()=>Object.entries(l).filter(([,N])=>N.status==="new"||N.status==="edited").map(([N,C])=>({name:N,status:C.status})),[l]),[f,y]=M(null),g=ae(N=>{y(C=>C===N?null:N)},[]),{pageGroups:x,componentGroups:v}=ne(()=>{var A;const N=new Map,C=new Map;for(const T of m)if(T.componentName){const P=C.get(T.componentName)||[];P.push(T),C.set(T.componentName,P)}else if(_o(T.url)){const P=(A=T.url)==null?void 0:A.match(/[?&]c=([^&]+)/),_=P?decodeURIComponent(P[1]):"Isolated",$=C.get(_)||[];$.push(T),C.set(_,$)}else{const P=nt(T.url),_=N.get(P)||[];_.push(T),N.set(P,_)}return{pageGroups:N,componentGroups:C}},[m]),b=ne(()=>xi([...x.entries()],l),[x,l]),w=ne(()=>xi([...v.entries()],l),[v,l]),S=b,E=w,k=ne(()=>Jh(r,l),[r,l]);return m.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:i,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),p&&n("div",{className:"text-[11px] text-gray-400 truncate",title:p,children:p})]}),n("button",{onClick:i,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),u&&n(gc,{text:u,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:d("div",{className:"space-y-5",children:[S.length>0&&d("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:S.map(([N,C])=>{var _;const A=l[N],T=f===N,P=(_=C[0])==null?void 0:_.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:N}),A&&n(mi,{status:A,onClick:()=>g(N)})]}),T&&(A==null?void 0:A.status)==="edited"&&P&&n(hi,{filePath:P}),T&&(A==null?void 0:A.status)==="impacted"&&n(fi,{impactedBy:A.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:C.map($=>n(gi,{scenarioId:$.id,name:yi($.name),isActive:$.id===o,onSelect:()=>a($)},$.id))})]},N)})})]}),E.length>0&&d("div",{className:S.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:E.map(([N,C])=>{var _;const A=l[N],T=f===N,P=(_=C[0])==null?void 0:_.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:N}),A&&n(mi,{status:A,onClick:()=>g(N)})]}),T&&(A==null?void 0:A.status)==="edited"&&P&&n(hi,{filePath:P}),T&&(A==null?void 0:A.status)==="impacted"&&n(fi,{impactedBy:A.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:C.map($=>n(gi,{scenarioId:$.id,name:yi($.name),isActive:$.id===o,onSelect:()=>a($)},$.id))})]},N)})})]}),k.length>0&&d("div",{className:S.length>0||E.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:k.map(N=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:N.name})}),n(kv,{filePath:N.filePath,projectRoot:s}),N.testFile?n(Ev,{testFile:N.testFile,entityName:N.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},N.name))})]}),c.length>0&&d("div",{className:S.length>0||E.length>0||k.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",c.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:c.map(N=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${N.status==="added"||N.status==="untracked"?"text-green-600":N.status==="modified"?"text-blue-600":N.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:N.status==="added"||N.status==="untracked"?"A":N.status==="modified"?"M":N.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:N.path})]},N.path))})]})]})})]})}function Pv({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 o=s===e.length-1;return d("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"})}),o?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 _v=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"journal",label:"Journal"}];function jv({activeTab:e,onTabChange:t,buildIdle:r,zoomComponent:s,breadcrumbItems:o,onBreadcrumbNavigate:a}){return d("div",{className:"bg-[#3d3d3d] h-10 flex items-center px-3 gap-3 shrink-0 z-20 border-b border-[#2d2d2d]",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:Br,alt:"CodeYam",className:"h-5 brightness-0 invert"}),n("span",{className:"text-white font-medium text-xs whitespace-nowrap",children:"Codeyam Editor"}),s&&d(ue,{children:[n("div",{className:"w-px h-3.5 bg-gray-600"}),n(Pv,{items:o,onNavigate:a})]})]}),n("div",{className:"flex-1"}),n("div",{className:"flex items-center gap-0.5 bg-[#4a3232] rounded-lg p-0.5 shrink-0",children:_v.map(i=>d("button",{onClick:()=>t(i.key),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors cursor-pointer ${e===i.key?"bg-[#7a4444] text-white":"text-gray-300 hover:text-white"}`,children:[i.label,i.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},i.key))})]})}function Mv({preview:e,onDismiss:t,onLoadCommit:r}){return d("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[d("div",{className:"text-center",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg overflow-hidden border-2 border-[#ccc] shadow-md max-w-full w-fit",children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"max-w-full h-auto block"})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3",children:e.commitSha&&r&&n(Tv,{commitSha:e.commitSha,onLoadCommit:r})})]})}function Tv({commitSha:e,onLoadCommit:t}){const[r,s]=M(!1),[o,a]=M(null);return d(ue,{children:[n("button",{onClick:()=>{s(!0),a(null),t(e).then(i=>{i.success||a(i.error||"Failed to load commit")}).catch(i=>{a(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Reverting...":"Revert to this code and load this version"}),o&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:o})]})}function $v({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,onStateChange:a}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=dn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:o,enabled:!0});return te(()=>{a(i,l||c)},[i,l,c,a]),null}function Rv(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function Iv(){const[e,t]=M({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),r=be(e);r.current=e,te(()=>{let a=!1,i=null;const l=async()=>{try{const c=await fetch("/api/editor-dev-server");if(a)return;const p=await c.json(),u=Rv(r.current,p),{shouldAutoStart:m,...h}=u;if(t(h),m)try{const f=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(a)return;f.ok?t(y=>({...y,isStarting:!0})):t(y=>({...y,canStartServer:!1}))}catch{}}catch{}};return l(),i=setInterval(()=>void l(),2e3),()=>{a=!0,i&&clearInterval(i)}},[e.url]);const s=ae(()=>{t(a=>({...a,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),o=ae(()=>{t(a=>({...a,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:e.url,proxyUrl:e.proxyUrl,isStarting:e.isStarting,error:e.error,canStartServer:e.canStartServer,retryServer:s,startServer:o}}function Dv(e){return e.filter(t=>t.testFile&&t.returnType!=="JSX.Element"&&t.returnType!=="React.ReactNode").map(t=>({name:t.name,filePath:t.filePath,description:t.description||"",testFile:t.testFile,feature:t.feature}))}function bi(e,t){var r,s,o,a,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((o=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&o[0])&&!((a=e.metadata)!=null&&a.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function Ov(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var m;const s=r.analyses[0],o=s.scenarios||[],a=!((m=s.status)!=null&&m.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=o.filter(h=>bi(h,l)),p=o.filter(h=>!bi(h,l)),u=t.find(h=>h.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:a,scenarioCount:o.length,scenarios:c.map(h=>{var f,y;return{id:h.id,name:h.name,description:h.description||"",screenshotPath:((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:p.map(h=>h.name),testFile:u==null?void 0:u.testFile}})}function Lv(e,t){var s;const r={};for(const o of e){const i=(((s=o.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[o.name]=i)}return r}const Fv=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function zv({request:e}){var S;const t=await Te();let r=!1,s=[],o=[];if(t){const{project:E}=await $e(t);r=((S=E.metadata)==null?void 0:S.editorMode)??!1;try{const k=Me();for(const P of["component_name","component_path","screenshot_path","url","viewport_width","viewport_height"])try{await k.schema.alterTable("editor_scenarios").addColumn(P,"varchar").execute()}catch{}const N=await k.selectFrom("editor_scenarios").selectAll().where("project_id","=",E.id).orderBy("created_at","asc").execute(),C=P=>({id:P.id,name:P.name,description:P.description||"",componentName:P.component_name||null,componentPath:P.component_path||null,screenshotPath:P.screenshot_path||null,url:P.url||null,type:P.type||null,viewportWidth:P.viewport_width||null,viewportHeight:P.viewport_height||null});o=kt(N,P=>`${P.name}::${P.url||"/"}`).map(C);const A=pe()||process.cwd(),T=Lg(A);if(T){const P=No(T),_=N.filter($=>$.created_at>=P);s=kt(_,$=>`${$.name}::${$.url||"/"}`).map(C)}else s=o}catch{}}const a=[...new Set(o.map(E=>E.componentName).filter(E=>E!==null))];let i=[];try{const E=pe()||process.cwd(),k=F.join(E,".codeyam","glossary.json");if(K.existsSync(k)){const N=K.readFileSync(k,"utf8");i=JSON.parse(N)}}catch{}const l=Dv(i);let c=[];try{const E=await cn()||[];c=Ov(E,i)}catch{}let p=[];try{if(c.length>0){const E=c.map(k=>k.sha);await ze(),p=await et({shas:E})||[]}}catch{}let u={};try{if(p.length>0){const E=new Set([...c.map(k=>k.name),...a,...l.map(k=>k.name)]);u=Lv(p,E)}}catch{}let m={};try{const E=pe()||process.cwd();m=scanPageFilePaths(E)}catch{}let h={};try{h=(await rs({projectRoot:pe()||process.cwd(),scenarioInputs:o,glossaryInputs:l})).entityChangeStatus}catch{}let f=[];try{f=kn().filter(k=>k.status!=="deleted").map(k=>({path:k.path,status:k.status}))}catch{}const y=pe()||process.cwd(),g=Jl(y),x=Hl(y);let v=null,b=null,w=null;try{const E=F.join(y,".codeyam","config.json");if(K.existsSync(E)){const k=JSON.parse(K.readFileSync(E,"utf8"));v=k.projectTitle||null,b=k.projectDescription||null,w=k.defaultScreenSize||null}}catch{}return Q({projectSlug:t,projectRoot:pe(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:o,components:a,analyzedEntities:c,glossaryFunctions:l,entityImports:u,pageFilePaths:m,entityChangeStatus:h,modifiedFiles:f,featureName:g,userPrompt:x,projectTitle:v,projectDescription:b,defaultScreenSize:w})}class Bv extends Lc{constructor(){super(...arguments);Mn(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:d("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&d("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const $s=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],Yv=We(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:o,allScenarios:a,analyzedEntities:i,glossaryFunctions:l,entityImports:c,pageFilePaths:p,entityChangeStatus:u,modifiedFiles:m,featureName:h,userPrompt:f,projectTitle:y,projectDescription:g,defaultScreenSize:x}=Ve(),v=ht(),[b,w]=vn(),S=be(null),E=be(null),k=be(null),N=b.get("zoom")||void 0,C=b.get("scenario")||void 0,A=be(null);te(()=>{if(!jm(C,A.current))return;const se=a.find(ke=>ke.id===C);if(!se)return;A.current=C;const Ne=Ct(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ne,scenarioId:se.id,scenarioName:se.name,scenarioType:se.type})}).catch(()=>{})},[C,a]),te(()=>{const se=new BroadcastChannel("codeyam-editor");return se.onmessage=Ne=>{var ke;if(((ke=Ne.data)==null?void 0:ke.type)==="switch-scenario"&&Ne.data.scenarioId){const Ie=Ne.data.scenarioId,Ze=a.find(pn=>pn.id===Ie);if(!Ze)return;A.current=Ie;const Vt=new URLSearchParams(b);Vt.set("scenario",Ie),Vt.delete("zoom"),w(Vt),D(null),j(null),Z(null),xt(!0);const cs=Ct(Ze.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:cs,scenarioId:Ie,scenarioType:Ze.type})}).then(()=>{dt(pn=>pn+1)}).catch(()=>{xt(!1)})}},()=>se.close()},[b,w,a]),te(()=>{if(b.get("ref")!=="link"||!C)return;const se=new BroadcastChannel("codeyam-editor");se.postMessage({type:"switch-scenario",scenarioId:C}),se.close(),window.close()},[]);const{devServerUrl:T,proxyUrl:P,isStarting:_,error:$,canStartServer:I,retryServer:R,startServer:Y}=Iv(),[H,W]=M(!1),[B,D]=M(null),[O,j]=M(null),[q,V]=M(!1),[U,Z]=M(null),z=ae(async se=>{const ke=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:se})})).json();return ke.success&&(Z(null),W(!1)),ke},[]),L=ae((se,Ne)=>{j(ke=>(se&&se!==ke&&W(!1),se)),!Ne&&se&&W(!0),V(Ne)},[]),J=ae(se=>{Z(null),D(ke=>(ke&&ke.analysisId===se.analysisId||(j(null),dt(Ze=>Ze+1)),se)),V(!0),W(!1);const Ne=new URLSearchParams(b);Ne.delete("scenario"),Ne.delete("zoom"),w(Ne)},[b,w]),[G,X]=M(x?{name:x.name,width:x.width,height:x.height}:{name:"Desktop",width:1440,height:900}),[le,xe]=M(!1),[oe,me]=M("app"),Ce=ae(()=>{me("build"),je(!0)},[]),[Re,je]=M(!1),[De,Le]=M(!1),Ee=ae(se=>{Le(se)},[]),[re,ye]=M(!1),Se=ae(()=>{ye(!0),me("build"),je(!0)},[]),ct=ae(()=>{ye(!1)},[]),[he,Be]=M(!1),Je=ae(()=>{if(he){Be(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(se=>{se==="granted"&&Be(!0)}):Be(!0)},[he]);te(()=>{if(oe==="build"){Le(!1);const se=setTimeout(()=>{var Ne,ke;(Ne=S.current)==null||Ne.scrollToBottom(),(ke=S.current)==null||ke.focus()},50);return()=>clearTimeout(se)}},[oe]);const[yt,Go]=M(null);te(()=>{const se=k.current;if(!se)return;const Ne=new ResizeObserver(ke=>{const Ie=ke[0];Ie&&Go({width:Ie.contentRect.width,height:Ie.contentRect.height})});return Ne.observe(se),()=>Ne.disconnect()},[]);const Jt=ne(()=>yt?Mm(yt,G):1,[yt,G]),[qo,dt]=M(0),[$t,En]=M(null),[un,xt]=M(!1),An=ae((se,Ne)=>{if(En(se||null),Ne){const ke=new URLSearchParams(b);ke.set("scenario",Ne),A.current=Ne,w(ke)}Z(null),dt(ke=>ke+1)},[b,w]),{customSizes:Qe,addCustomSize:bt}=Xr(t);ne(()=>[...$s,...Qe],[Qe]),te(()=>{const se=new EventSource("/api/events");let Ne=null;return se.addEventListener("message",ke=>{try{const Ie=JSON.parse(ke.data);(Ie.type==="db-change"||Ie.type==="unknown")&&(Ne&&clearTimeout(Ne),Ne=setTimeout(()=>{v.revalidate()},2e3))}catch{}}),()=>{Ne&&clearTimeout(Ne),se.close()}},[v]);const qe=ne(()=>{const se=[{name:"App"}];return N&&se.push({name:N,componentName:N}),se},[N]),Ue=ae(se=>{const Ne=new URLSearchParams(b);if(se){Ne.set("zoom",se);const ke=a.find(Ie=>Ie.componentName===se||Ie.componentName===null&&se==="Home");if(ke){Ne.set("scenario",ke.id),A.current=ke.id,xt(!0);const Ie=Ct(ke.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ie,scenarioId:ke.id,scenarioType:ke.type})}).then(()=>{dt(Ze=>Ze+1)}).catch(()=>{xt(!1)})}else Ne.delete("scenario")}else Ne.delete("zoom"),Ne.delete("scenario");w(Ne)},[b,w,a]),Ht=ae(se=>{if(D(null),j(null),Z(null),se.viewportWidth&&se.viewportHeight){const Ie=$s.find(Ze=>Ze.width===se.viewportWidth&&Ze.height===se.viewportHeight);X({name:(Ie==null?void 0:Ie.name)||"Custom",width:se.viewportWidth,height:se.viewportHeight})}A.current=se.id;const Ne=new URLSearchParams(b);Ne.set("scenario",se.id),w(Ne),xt(!0);const ke=Ct(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:ke,scenarioId:se.id,scenarioType:se.type})}).then(()=>{dt(Ie=>Ie+1)}).catch(()=>{xt(!1)})},[b,w]),Pn=ae(se=>{if(!se.commitSha){const Ne=a.find(ke=>ke.name===se.scenarioName);if(Ne){Ht(Ne);return}}Z(se)},[a,Ht]),Xn=se=>{X({name:se.name,width:se.width,height:se.height})},is=se=>{bt(se,G.width,G.height??900),xe(!1),X(Ne=>({...Ne,name:se}))},er=()=>{B||W(!0),xt(!1)},Rt=ne(()=>_m({activeAnalyzedScenario:!!B,analyzedPreviewUrl:O,activeScenarioId:C||null,scenarios:a,proxyUrl:P,devServerUrl:T,zoomComponent:N||null}),[P,T,N,C,a,B,O]),tr=ne(()=>gl(Rt,$t),[Rt,$t]),ls=ne(()=>({projectSlug:t,hasProject:s,scenarioCount:o==null?void 0:o.length,allScenarioCount:a==null?void 0:a.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:l==null?void 0:l.length,entityChangeStatusKeys:u?Object.keys(u):[],featureName:h}),[t,s,o,a,i,l,u,h]);return n(Bv,{loaderSnapshot:ls,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[B&&n($v,{analysisId:B.analysisId,scenarioId:B.scenarioId,scenarioName:B.scenarioName,entityName:B.entityName,projectSlug:t,onStateChange:L},B.analysisId),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[n("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center px-4 gap-1",children:d("div",{className:"flex-1 flex items-center justify-center gap-1",children:[$s.map(se=>d("button",{onClick:()=>Xn(se),className:`p-1.5 rounded transition-colors cursor-pointer ${G.name===se.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${se.name} (${se.width}×${se.height})`,children:[se.name==="Desktop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),se.name==="Laptop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),se.name==="Tablet"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),se.name==="Mobile"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},se.name)),n("button",{onClick:()=>xe(!0),className:`p-1.5 rounded transition-colors cursor-pointer ${G.name==="Custom"?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:"Custom dimensions",children:n("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),d("span",{className:"text-gray-400 text-xs font-mono",children:[G.width," × ",G.height??900]}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),n("button",{onClick:()=>{const se=tr||Rt;se&&window.open(se,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})}),n("div",{ref:k,className:"flex-1 flex items-center justify-center overflow-hidden p-8",style:U?{backgroundColor:"#f5f0e8",backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px), repeating-linear-gradient(90deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px)"}:{backgroundImage:`
|
|
336
|
+
linear-gradient(45deg, #333 25%, transparent 25%),
|
|
337
|
+
linear-gradient(-45deg, #333 25%, transparent 25%),
|
|
338
|
+
linear-gradient(45deg, transparent 75%, #333 75%),
|
|
339
|
+
linear-gradient(-45deg, transparent 75%, #333 75%)
|
|
340
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:U?n(Mv,{preview:U,onDismiss:()=>Z(null),onLoadCommit:z}):Rt?n("div",{style:{width:`${G.width*Jt}px`,height:`${(G.height??900)*Jt}px`},children:d("div",{className:"relative bg-white origin-top-left",style:{width:`${G.width}px`,height:`${G.height??900}px`,transform:Jt<1?`scale(${Jt})`:void 0},children:[!H&&!un&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),un&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:E,src:tr||Rt,className:"w-full h-full border-none",title:"Editor preview",onLoad:er,style:{opacity:H?1:0}},qo)]})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${G.width*Jt}px`,height:`${(G.height??900)*Jt}px`},children:$?d("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:$}),n("button",{onClick:R,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"})]}):_||q?d(ue,{children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:q?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:q?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]}),d("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:[n(jv,{activeTab:oe,onTabChange:se=>{me(se),se==="build"&&je(!0)},buildIdle:De,zoomComponent:N,breadcrumbItems:qe,onBreadcrumbNavigate:Ue}),d("div",{className:"flex-1 overflow-hidden relative",children:[Re&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:oe==="build"?"visible":"hidden"},children:[n("div",{className:re?"flex-1 min-h-0":"flex-1",style:re?{flex:"1 1 50%"}:void 0,children:n(fl,{ref:S,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:An,onShowResults:Se,onHideResults:ct,editorMode:!0,onIdleChange:Ee,notificationsEnabled:he})}),re&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(Av,{scenarios:o,allScenarios:a,glossaryFunctions:l,projectRoot:r,activeScenarioId:C,onScenarioSelect:Ht,onClose:ct,entityChangeStatus:u,modifiedFiles:m,featureName:h,userPrompt:f})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:oe==="app"?"visible":"hidden"},children:n(Sv,{hasProject:s,scenarios:a,analyzedEntities:i,glossaryFunctions:l,projectRoot:r,activeScenarioId:C,onScenarioSelect:Ht,onAnalyzedScenarioSelect:J,onSwitchToBuild:Ce,zoomComponent:N,onZoomChange:Ue,entityImports:c,pageFilePaths:p,projectTitle:y,projectDescription:g})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:oe==="data"?"visible":"hidden"},children:n(hv,{scenarios:a,projectRoot:r,activeScenarioId:C,onScenarioSelect:Ht,zoomComponent:N,onZoomChange:Ue,analyzedEntities:[],glossaryFunctions:l,activeAnalyzedScenarioId:B==null?void 0:B.scenarioId,onAnalyzedScenarioSelect:J,entityImports:c,pageFilePaths:p})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:oe==="journal"?"visible":"hidden"},children:n(Cv,{isActive:oe==="journal",onScreenshotClick:Pn,glossaryFunctions:l})})]}),n(hl,{serverUrl:T,isStarting:_,projectSlug:t,devServerError:$,onStartServer:I?Y:void 0,notificationsEnabled:he,onToggleNotifications:Je})]})]}),le&&n(Zr,{width:G.width,height:G.height??900,onSave:is,onCancel:()=>xe(!1)})]})})}),Uv=Object.freeze(Object.defineProperty({__proto__:null,default:Yv,loader:zv,meta:Fv},Symbol.toStringTag,{value:"Module"}));function yc({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Fd,{remarkPlugins:[zd],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:o})=>(o==null?void 0:o.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(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:o})=>n("a",{href:o,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function xc(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let o=t,a="";for(const i of s)a=a?`${a}/${i}`:i,o.children.has(i)||o.children.set(i,{name:i,path:a,memories:[],children:new Map}),o=o.children.get(i);s.length===0?t.memories.push(r):o.memories.push(r)}return t}function bc(e){let t=e.memories.length;for(const r of e.children.values())t+=bc(r);return t}function as(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 Yn(e){return Math.round(e/3.5)}function fn(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),p=Math.floor(c/(1e3*60)),u=Math.floor(c/(1e3*60*60));return p<3?"Just now":p<60?`${p}min ago`:u===1?"1h ago":`${u}h ago`}const o=t.toLocaleDateString("en-US",{month:"short"}),a=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${o} ${a}`:`${o} ${a}, ${i}`}function Wv({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:o,onToggleReviewed:a,changeType:i,isUncommitted:l,changeDate:c,diff:p,isFadingOut:u,showLeftBorder:m}){const[h,f]=M(!1),[y,g]=M(!1),x=ne(()=>as(e.body,e.filePath),[e.body,e.filePath]),v=Yn(e.body.length),b=h?"#3e3e3e":l?"#d97706":"#c7c7c7",w=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,S={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:w,style:S,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!h),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:h?"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})})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),d("span",{className:"text-xs text-gray-400",children:["~",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&&d(ue,{children:[e.frontmatter.paths.slice(0,2).map((E,k)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:E},k)),e.frontmatter.paths.length>2&&d("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),d("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c&&n("span",{className:"text-xs text-gray-400",children:fn(c)}),a&&n("button",{onClick:E=>{E.stopPropagation(),a(e.filePath,e.lastModified,o??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${o?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:o?"Mark as unreviewed":"Mark as reviewed",children:o&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),h&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&p&&d("button",{onClick:E=>{E.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Nr,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("button",{onClick:E=>{E.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(dd,{className:"w-3 h-3"}),"Edit"]}),d("button",{onClick:E=>{E.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(ud,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&p&&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:p.split(`
|
|
341
|
+
`).map((E,k)=>{let N="";return E.startsWith("+")&&!E.startsWith("+++")?N="text-green-400":E.startsWith("-")&&!E.startsWith("---")?N="text-red-400":E.startsWith("@@")&&(N="text-cyan-400"),n("div",{className:N,children:E},k)})}),d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),d("div",{className:"flex items-center gap-2",children:[d("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(Mt,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((E,k)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:E},k))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(yc,{content:e.body})})]})]})}function Jv(){return new Date().toISOString().split(".")[0]+"",`---
|
|
342
|
+
paths:
|
|
343
|
+
- '**/*.ts'
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
## Title
|
|
347
|
+
|
|
348
|
+
Description here.
|
|
349
|
+
`}function Hv({rule:e,onSave:t,onCancel:r}){const[s,o]=M(e?`.claude/rules/${e.filePath}`:""),[a,i]=M((e==null?void 0:e.content)||Jv()),[l,c]=M(!!e),[p,u]=M(!1),m=!e;return d("div",{className:"p-6",children:[d("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Gn,{className:"w-5 h-5"})})]}),m&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(Nr,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),d("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),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:p?n(ft,{className:"w-4 h-4 text-green-500"}):n(St,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!m)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:h=>o(h.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(St,{className:"w-4 h-4"})})]})]}),e&&d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),d("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(St,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:a,onChange:h=>i(h.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),a),disabled:!s.trim()||!a.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Vv({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:o}){const a=ne(()=>xc(e),[e]),i=(p,u,m)=>{if(p.target.closest(".chevron-toggle")){m&&o(u||"root");return}const f=u||null;r(t===f?null:f),m&&!s.has(u||"root")&&o(u||"root")},l=p=>{r(t===p?null:p)},c=(p,u=0)=>{const m=s.has(p.path||"root"),h=bc(p),f=p.children.size>0,y=p.name==="root"?"(root)":p.name,g=p.memories.length>0||f,x=p.path||"",v=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,p.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),o(p.path||"root")},children:n(Yt,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(_i,{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}),d("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[h," rules"]})]}),m&&d("div",{className:"relative",children:[(p.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),p.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:p.memories.map(b=>{var S;const w=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${w?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(b.filePath),children:n("span",{className:"text-xs",children:(S=b.filePath.split("/").pop())==null?void 0:S.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(p.children.values()).sort((b,w)=>b.name.localeCompare(w.name)).map(b=>c(b,u+1))})]})]},p.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(a)})}function Gv({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:o,reviewedStatus:a,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[p,u]=M({});te(()=>{u({})},[a]);const m=ne(()=>({...a,...p}),[a,p]),h=ne(()=>xc(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?l(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,S=g.memories.length>0||b;return d("div",{children:[d("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>S&&o(g.path||"root"),children:[S&&n(Yt,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!S&&n("div",{className:"w-4"}),n(_i,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:w})]}),v&&d("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(E=>n(Wv,{rule:E,onEdit:t,onDelete:r,onView:c,isReviewed:m[E.filePath]??!1,onToggleReviewed:f},E.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((E,k)=>E.name.localeCompare(k.name)).map(E=>y(E,x+1))})]})]},g.path||"root")};return n("div",{children:y(h)})}function qv({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[o,a]=M("unreviewed"),[i,l]=M("by-date"),[c,p]=M(null),[u,m]=M(!0),[h,f]=M(new Map),y=be(t),g=be([]);te(()=>()=>{g.current.forEach(clearTimeout)},[]),te(()=>{(async()=>{m(!0);try{const k=await(await fetch("/api/memory?action=rule-coverage")).json();p(k.coverage??null)}catch{p(null)}finally{m(!1)}})()},[s]),te(()=>{const S=y.current,E=[];for(const[k,N]of Object.entries(t))N&&!S[k]&&E.push(k);y.current=t,E.length!==0&&(f(k=>{const N=new Map(k);return E.forEach(C=>N.set(C,"approved")),N}),g.current.push(setTimeout(()=>{f(k=>{const N=new Map(k);return E.forEach(C=>N.set(C,"fading")),N})},1500)),g.current.push(setTimeout(()=>{f(k=>{const N=new Map(k);return E.forEach(C=>N.delete(C)),N})},2500)))},[t]);const x=ne(()=>{const S=[...e];return i==="by-impact"&&c!==null?S.sort((E,k)=>{const N=c[E.filePath]??0,C=c[k.filePath]??0;return C!==N?C-N:new Date(k.lastModified).getTime()-new Date(E.lastModified).getTime()}):S.sort((E,k)=>new Date(k.lastModified).getTime()-new Date(E.lastModified).getTime()),S},[e,i,c]),v=ne(()=>x.filter(S=>!t[S.filePath]).length,[x,t]),b=ne(()=>o==="unreviewed"?x.filter(S=>!t[S.filePath]||h.has(S.filePath)):x,[x,o,t,h]),w=!u&&c!==null;return d("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),d("button",{onClick:()=>a("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="unreviewed"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="unreviewed"?600:400,color:o==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),d("button",{onClick:()=>a("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="all"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="all"?600:400,color:o==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),d("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),d("button",{onClick:()=>w&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${w?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(lt,{className:"w-3 h-3"})]}),d("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(lt,{className:"w-3 h-3"})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",d("span",{className:"relative group",children:[n(Is,{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(S=>{const E=t[S.filePath]??!1,k=h.get(S.filePath),N=as(S.body,S.filePath),C=(c==null?void 0:c[S.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${k==="fading"?"duration-1000":"duration-300"}`,style:{opacity:k==="fading"?0:1},children:d("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${k==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(S),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:N})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:C>0?"text-gray-700 font-medium":"text-gray-300",children:C}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:fn(S.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 ${E?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:E&&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"})})})})]})},S.filePath)})}),b.length===0&&o==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function Kv(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
350
|
+
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
351
|
+
|
|
352
|
+
${r}
|
|
353
|
+
|
|
354
|
+
Please review these rules in conjunction with one another as they all apply to this file.
|
|
355
|
+
|
|
356
|
+
Review each rule with the other rules in mind:
|
|
357
|
+
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
358
|
+
- Efficiency: Are the rules concise and well-structured?
|
|
359
|
+
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
360
|
+
- Context window impact: Can the rules be shortened without losing important information?
|
|
361
|
+
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
362
|
+
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
363
|
+
|
|
364
|
+
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
365
|
+
|
|
366
|
+
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 Qv({filePath:e,rulePaths:t,onClose:r}){const[s,o]=M(!1),a=Kv(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Gn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:a,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(a),o(!0),setTimeout(()=>o(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?d(ue,{children:[n(ft,{className:"w-4 h-4"}),"Copied!"]}):d(ue,{children:[n(St,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function Zv({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[o,a]=M("unreviewed"),[i,l]=M(null),[c,p]=M(""),[u,m]=M(0),[h,f]=M(!1),[y,g]=M(null),[x,v]=M(null),b=be(null),w=be(null),[S,E]=M({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[k,N]=M(!0);te(()=>{(async()=>{N(!0);try{const H=await(await fetch("/api/memory?action=audit")).json();E({topPaths:H.topPaths||[],totalFilesWithCoverage:H.totalFilesWithCoverage||0,allSourceFiles:H.allSourceFiles||[]})}catch(Y){console.error("Failed to load audit data:",Y)}finally{N(!1)}})()},[e]);const C=ne(()=>o==="all"?S.topPaths:S.topPaths.filter(R=>R.matchingRules.some(Y=>!t[Y.filePath])),[S.topPaths,o,t]);ne(()=>S.topPaths.filter(R=>R.matchingRules.some(Y=>!t[Y.filePath])).length,[S.topPaths,t]);const A=R=>R.split("/").pop()||R,T=ne(()=>{const R=new Map;for(const Y of S.topPaths)R.set(Y.filePath,Y);return R},[S.topPaths]),P=ne(()=>{if(!c.trim())return[];const R=c.toLowerCase(),Y=[],H=[];for(const W of S.allSourceFiles){const B=W.toLowerCase();if(!B.includes(R))continue;const D=T.get(W)||{filePath:W,matchingRules:[],totalTextLength:0};B.startsWith(R)?Y.push(D):H.push(D)}return Y.sort((W,B)=>W.filePath.localeCompare(B.filePath)),H.sort((W,B)=>W.filePath.localeCompare(B.filePath)),[...Y,...H].slice(0,8)},[c,S.allSourceFiles,T]),_=ae(R=>{var Y;g(R),l(R.filePath),p(R.filePath),f(!1),(Y=b.current)==null||Y.blur()},[]),$=ae(()=>{var R;p(""),g(null),l(null),(R=b.current)==null||R.focus()},[]),I=ae(R=>{var Y;!h||P.length===0||(R.key==="ArrowDown"?(R.preventDefault(),m(H=>Math.min(H+1,P.length-1))):R.key==="ArrowUp"?(R.preventDefault(),m(H=>Math.max(H-1,0))):R.key==="Enter"?(R.preventDefault(),_(P[u])):R.key==="Escape"&&(f(!1),(Y=b.current)==null||Y.blur()))},[h,P,u,_]);return te(()=>{m(0)},[P]),d("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),d("div",{className:"relative flex-1 max-w-[300px]",children:[n(Vn,{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:c,onChange:R=>{p(R.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:I,placeholder:"Search files...",className:`w-full pl-8 ${c?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),c&&n("button",{type:"button",onMouseDown:R=>{R.preventDefault(),$()},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"})})}),h&&P.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:P.map((R,Y)=>d("div",{onMouseDown:H=>{H.preventDefault(),_(R)},onMouseEnter:()=>m(Y),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${Y===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Cr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:R.filePath,children:(()=>{const H=R.filePath.toLowerCase().indexOf(c.toLowerCase());if(H===-1)return R.filePath;const W=R.filePath.slice(0,H),B=R.filePath.slice(H,H+c.length),D=R.filePath.slice(H+c.length);return d(ue,{children:[W,n("span",{className:"font-semibold text-[#005C75]",children:B}),D]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[R.matchingRules.length," rule",R.matchingRules.length!==1?"s":""]})]},R.filePath))})]}),n("div",{className:"flex-1"}),d("button",{onClick:()=>a("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="unreviewed"?600:400,color:o==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),d("button",{onClick:()=>a("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:o==="all"?600:400,color:o==="all"?"#005C75":"#626262"},children:"All"})]})]}),d("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",d("span",{className:"relative group",children:[n(Is,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",d("span",{className:"relative group",children:[n(Is,{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"})]})]})]}),k&&n("div",{className:"px-5 py-6",children:d("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!k&&(C.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...C.filter(Y=>Y.filePath!==y.filePath)].slice(0,8):C.slice(0,8)).map((R,Y)=>{const H=R.matchingRules.length,W=R.matchingRules.filter(V=>!t[V.filePath]),B=W.length,D=W.reduce((V,U)=>V+U.bodyLength,0),O=B>0,j=i===R.filePath,q=(y==null?void 0:y.filePath)===R.filePath;return d("div",{children:[d("div",{onClick:()=>l(j?null:R.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${q?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[d("div",{className:"flex items-center gap-2 min-w-0",children:[j?n(lt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Yt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Cr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:R.filePath,children:q?R.filePath:A(R.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:O?"font-semibold text-[#1A5276]":"text-gray-400",children:B}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:H})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:O?"font-semibold text-[#1A5276]":"text-gray-400",children:Yn(D).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Yn(R.totalTextLength).toLocaleString()})]})]}),j&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[R.matchingRules.map(V=>{const U=r.find(z=>z.filePath===V.filePath),Z=t[V.filePath]??!1;return d("div",{onClick:z=>{z.stopPropagation(),U&&s(U)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(wr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:U?as(U.body,U.filePath):V.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Yn(V.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${Z?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:Z&&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"})})})]},V.filePath)}),d("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:V=>{V.stopPropagation(),v({filePath:R.filePath,rulePaths:R.matchingRules.map(U=>U.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},R.filePath)})}),!k&&C.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:o==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(Qv,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function Xv({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:o,onDelete:a,onClose:i}){const l=as(e.body,e.filePath),c=Yn(e.body.length),p=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[m,h]=M(null),f=(t==null?void 0:t.changeType)==="added"||m!=null&&m.commitCount!=null&&m.commitCount<=1&&!(m.commitCount===1&&m.isUncommitted);return te(()=>{h(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&h(y.diff)}).catch(()=>{})},[e.filePath]),te(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:d("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"min-w-0 flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&d(ue,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:fn(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})]})]}),p&&d("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:p})]}),d("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(Mt,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),d("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",c.toLocaleString()]})]}),d("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[d("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(ft,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(Gn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),v=x.pop()||y,b=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Cr,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("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:d("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?fn(t.date):m!=null&&m.date?fn(m.date):"recently"]})}):m&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",m.commitMessage," —"," ",fn(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(`
|
|
367
|
+
`).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),d("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(yc,{content:e.body})})]})]})})}function ew(){return d("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function tw(){return d("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function nw(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[d("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),d("ol",{className:"space-y-5",children:[d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),d("div",{children:[d("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(vi,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),d("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),d("div",{className:"space-y-6",children:[d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[d("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),d("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(vi,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function vi({value:e}){const[t,r]=M(!1);return d("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(ft,{className:"w-3.5 h-3.5 text-green-400"}):d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function fr({label:e,count:t,icon:r,bgColor:s,iconBgColor:o,textColor:a}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:d("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:o},children:r}),d("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:a},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:a},children:e})]})]})})}function rw({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:o}){return d("div",{className:"mb-8",children:[d("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[d("div",{children:[d("div",{className:"flex items-center gap-3 mb-2",children:[n(ew,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),d("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),d("div",{className:"flex items-center gap-3",children:[d("div",{className:"relative",children:[n(Vn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:a=>t(a.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),d("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(oo,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(fr,{label:"Total Rules",count:o.total,icon:n(tw,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(fr,{label:"Unreviewed",count:o.unreviewed,icon:n(pd,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(fr,{label:"Reviewed",count:o.reviewed,icon:n(ft,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(fr,{label:"Stale",count:o.stale,icon:n(Pi,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function sw({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Gn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),d("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[d("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:d("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(oo,{className:"w-4 h-4"}),"New Rule"]})})]})})}function ow({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:d("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),d("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const wi="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",Ni="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Ci({text:e}){const[t,r]=M(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(ue,{children:[n(ft,{className:"w-4 h-4"}),"Copied!"]}):d(ue,{children:[n(St,{className:"w-4 h-4"}),"Copy Prompt"]})})}function aw({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Gn,{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:wi,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(Ci,{text:wi})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Ni,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(Ci,{text:Ni})})]})]})})}function iw(){const[e,t]=M(!1);return d(ue,{children:[d("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(aw,{onClose:()=>t(!1)})]})}const lw=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function cw({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?Q({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?Q({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const dw=We(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:o}=Ve(),a=Oe(),i=ht(),[l,c]=M(""),[p,u]=M(null),[m,h]=M(new Set(["root"])),[f,y]=M(null),[g,x]=M(!1),[v,b]=M(null),[w,S]=M(0),[E,k]=M(!1),[N,C]=M(null),[A,T]=M(null),[P,_]=M({}),$=z=>{h(L=>{const J=new Set(L);return J.has(z)?J.delete(z):J.add(z),J})};gt({source:"memory-page"});const I=ne(()=>({...r,...P}),[r,P]),R=be(a.state);te(()=>{const z=R.current==="loading"||R.current==="submitting",L=a.state==="idle";z&&L&&a.data&&(i.revalidate(),y(null),x(!1),S(J=>J+1)),R.current=a.state},[a.state,a.data,i]),te(()=>{_(z=>{const L={};for(const[J,G]of Object.entries(z))r[J]!==G&&(L[J]=G);return Object.keys(L).length===Object.keys(z).length?z:L})},[r]);const Y=(z,L)=>{_(J=>({...J,[z]:!0})),a.submit({action:"mark-reviewed",filePath:z,lastModified:L},{method:"POST",action:"/api/memory",encType:"application/json"})},H=z=>{_(L=>({...L,[z]:!1})),a.submit({action:"mark-unreviewed",filePath:z},{method:"POST",action:"/api/memory",encType:"application/json"})},W=(z,L)=>{C(z),T(L??null)},B=ne(()=>{let z=t;if(l.trim()){const L=l.toLowerCase();z=z.filter(J=>{var X;return(((X=J.filePath.split("/").pop())==null?void 0:X.replace(".md",""))||"").toLowerCase().includes(L)||J.body.toLowerCase().includes(L)})}return z},[t,l]),D=ne(()=>p?B.some(L=>L.filePath===p)?B.filter(L=>L.filePath===p):B.filter(L=>L.filePath.startsWith(p+"/")||L.filePath===p):B,[B,p]),O=(z,L)=>{const J=f?"update":"create";a.submit({action:J,filePath:z,content:L},{method:"POST",action:"/api/memory",encType:"application/json"})},j=z=>{a.submit({action:"delete",filePath:z.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},q=ne(()=>{const z=t.filter(L=>I[L.filePath]).length;return{total:t.length,reviewed:z,unreviewed:t.length-z,stale:0}},[t,I]),V=ne(()=>{const z=new Set(["root"]);for(const L of B){const J=L.filePath.split("/");J.pop();let G="";for(const X of J)G=G?`${G}/${X}`:X,z.add(G)}return z},[B]),U=V.size===m.size&&[...V].every(z=>m.has(z)),Z=()=>{h(U?new Set(["root"]):new Set(V))};return o?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:o})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(rw,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>k(!0),reviewCounts:q}),(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:z=>z.stopPropagation(),children:n(Hv,{rule:f,onSave:O,onCancel:()=>{x(!1),y(null)}})})}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(qv,{memories:B,reviewedStatus:I,onViewRule:W,refreshKey:w}),n(Zv,{onEditRule:y,onDeleteRule:b,refreshKey:w,reviewedStatus:I,onMarkReviewed:Y,onMarkUnreviewed:H,memories:t,onViewRule:W})]}),n(iw,{}),d("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:V.size>1&&n("button",{onClick:Z,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:U?"Collapse All":"Expand All"})})]}),d("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Vv,{memories:B,selectedPath:p,onSelectPath:u,expandedFolders:m,onToggleFolder:$})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(md,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),d("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),d("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(oo,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[p&&d("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:p||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Gv,{memories:D,onEdit:y,onDelete:b,expandedFolders:m,onToggleFolder:$,reviewedStatus:I,onMarkReviewed:Y,onMarkUnreviewed:H,onViewRule:W})]})})]}),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:d("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),d("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),N&&!f&&(()=>{const z=t.find(L=>L.filePath===N.filePath)??N;return n(Xv,{rule:z,changeInfo:A??void 0,isReviewed:I[z.filePath]??!1,onApprove:()=>{I[z.filePath]??!1?H(z.filePath):Y(z.filePath,z.lastModified),C(null)},onEdit:()=>{y(z)},onDelete:()=>{b(z),C(null)},onClose:()=>C(null)})})(),E&&n(sw,{onClose:()=>k(!1),onCreateNew:()=>{k(!1),x(!0)}}),v&&n(ow,{rule:v,onConfirm:j,onCancel:()=>b(null)})]})}):n(nw,{})}),uw=Object.freeze(Object.defineProperty({__proto__:null,default:dw,loader:cw,meta:lw},Symbol.toStringTag,{value:"Module"}));function Rs(e){return`${e.filePath||""}::${e.name}`}function vc(e,t){const r=Oe(),{showToast:s}=ho(),[o,a]=M(new Map);te(()=>{if(r.state==="idle"&&r.data){const h=r.data;h!=null&&h.error&&s(`Error: ${h.error}`,"error",6e3)}},[r.state,r.data,s]),te(()=>{var f;if(o.size===0)return;const h=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{o.forEach((v,b)=>{v===x&&h.add(b)})})}),e==null||e.forEach(y=>{o.forEach((g,x)=>{g===y&&h.add(x)})}),h.size>0&&a(y=>{const g=new Map(y);return h.forEach(x=>g.delete(x)),g})},[t,e,o]);const i=ae(h=>{console.log("Generate analysis clicked for entity:",h.sha,h.name);const f=Rs(h);a(g=>new Map(g).set(f,h.sha));const y=new FormData;y.append("entitySha",h.sha),y.append("filePath",h.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=ae(h=>{const f=h.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),a(x=>{const v=new Map(x);return f.forEach(b=>v.set(Rs(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]),c=ae(h=>(e==null?void 0:e.includes(h))??!1,[e]),p=ae(h=>{const f=Rs(h);return o.has(f)},[o]),u=ae(h=>{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(h)}))??!1},[t]),m=ne(()=>Array.from(o.keys()),[o]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:p,isEntityInQueue:u,pendingEntityKeys:m}}function Wo({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:o=!1,analyzeAllText:a="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:d("div",{className:"flex justify-between items-center px-3 py-2",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),d("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),d("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:o,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:o?a:"Analyze all entities",children:a})})]})]})]})})}function pw({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const a=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:a.textColor},children:a.label})})}const o=r[e]||{label:"?",bgColor:"bg-gray-500"};return d("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${o.bgColor}`,title:e,children:o.label}),o.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Jo({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:o,entityCount:a,state:i,lastModified:l,actionButton:c,uncommittedCount:p,children:u,isNotAnalyzable:m=!1,isUncommitted:h=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${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:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Li,{filePath:e}),s&&n(pw,{status:typeof s=="string"?s:s.status,variant:"full"}),h&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(h||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[h&&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"&&!h&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:o}),d("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:d("span",{className:"text-[13px] text-[#3e3e3e]",children:[a," ",a===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:ac(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:c})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Ho({entities:e,maxPreviews:t=3}){var s,o,a,i,l;const r=[];for(const c of e){if(r.length>=t)break;const p=((o=(s=c.analyses)==null?void 0:s[0])==null?void 0:o.scenarios)||[];if(c.entityType==="library"){const u=p.find(m=>{var h,f;return((h=m.metadata)==null?void 0:h.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:c.sha})}else if(c.entityType==="visual"){const u=p.find(m=>{var h,f;return(f=(h=m.metadata)==null?void 0:h.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(a=u.metadata)==null?void 0:a.screenshotPaths)==null?void 0:i[0],h=!!((l=u.metadata)!=null&&l.error);m&&r.push({type:"screenshot",screenshot:m,hasError:h,scenario:u,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((c,p)=>{if(c.type==="screenshot"&&c.screenshot){const u=c.hasError?"border-red-400":"border-gray-200";return d(de,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.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(Ge,{screenshotPath:c.screenshot,alt:`Preview ${p+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(vr,{size:12,color:"white"})})]},`screenshot-${p}`)}return c.type==="library"&&c.scenario&&c.entitySha?n(sc,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${p}`):null})})}function Vo({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,m;const o=t||r?[{entityShas:[e.sha]}]:[],a=ot(e,o,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(a==="not-analyzed"||a==="out-of-date")&&!t&&!r,p=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(h=>{var f,y;return(y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return d("div",{className:"bg-white rounded-lg",children:[d(de,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(tt,{type:"type"})})}):n(tt,{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(Io,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?a==="queued"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):a==="analyzing"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):a==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):a==="out-of-date"?n("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:h=>{h.preventDefault(),h.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"})})]})]})]}),p.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:p.map((h,f)=>{var g,x;const y=(x=(g=h.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(de,{to:`/entity/${e.sha}?scenario=${h.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(Ge,{screenshotPath:y,alt:h.name,className:"max-w-full max-h-full object-contain object-center"})},h.id):null})})]})}function mw({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:o,entityType:a,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:p,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:h,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=vn(),[b,w]=M(new Set),[S,E]=M(""),[k,N]=M(!1),[C,A]=M("all"),[T,P]=M("desc"),_=a||"all",$=ne(()=>{let j=e;return _!=="all"&&(j=j.filter(q=>q.entityType===_)),o==="analyzed"&&(j=j.filter(q=>q.analyses&&q.analyses.length>0)),j},[e,_,o]),I=ne(()=>{const j=new Map,q=new Map,V=new Map;$.forEach(L=>{var X,le;const J=`${L.filePath}::${L.name}`,G=q.get(J);if(!G)q.set(J,L),V.set(J,[]);else{const xe=((X=G.metadata)==null?void 0:X.editedAt)||G.createdAt||"",oe=((le=L.metadata)==null?void 0:le.editedAt)||L.createdAt||"";let me=!1;if(oe>xe)me=!0;else if(oe===xe){const Ce=G.createdAt||"";me=(L.createdAt||"")>Ce}me?(V.get(J).push(G),q.set(J,L)):V.get(J).push(L)}}),q.forEach((L,J)=>{var X;if(!(L.analyses&&L.analyses.length>0)&&((X=L.metadata)!=null&&X.previousVersionWithAnalyses)){const xe=(V.get(J)||[]).find(oe=>{var me;return oe.sha===((me=L.metadata)==null?void 0:me.previousVersionWithAnalyses)});xe&&xe.analyses&&xe.analyses.length>0&&(L.analyses=xe.analyses)}}),Array.from(q.values()).sort((L,J)=>{var le,xe,oe,me;const G=!((le=L.metadata)!=null&&le.notExported)&&!((xe=L.metadata)!=null&&xe.namedExport),X=!((oe=J.metadata)!=null&&oe.notExported)&&!((me=J.metadata)!=null&&me.namedExport);return G&&!X?-1:!G&&X?1:0}).forEach(L=>{var xe,oe,me,Ce,Re;const J=L.filePath??"No File Path";j.has(J)||j.set(J,{filePath:J,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=j.get(J);G.entities.push(L),G.totalCount++,(xe=L.metadata)!=null&&xe.isUncommitted&&G.uncommittedCount++;const X=((Ce=(me=(oe=L.analyses)==null?void 0:oe[0])==null?void 0:me.scenarios)==null?void 0:Ce.length)||0;G.simulationCount+=X;const le=((Re=L.metadata)==null?void 0:Re.editedAt)||L.updatedAt;le&&(!G.lastUpdated||new Date(le)>new Date(G.lastUpdated))&&(G.lastUpdated=le)});const U=(i==null?void 0:i.jobs)||[],Z=L=>{const J=`${L.filePath||""}::${L.name}`;return(c==null?void 0:c.includes(J))||!1};j.forEach(L=>{const J=L.entities.map(G=>Z(G)?"queued":ot(G,U));J.includes("analyzing")||J.includes("queued")?L.state="analyzing":J.includes("incomplete")?L.state="incomplete":J.includes("out-of-date")?L.state="out-of-date":J.includes("not-analyzed")?L.state="not-analyzed":L.state="up-to-date"}),j.forEach(L=>{var J,G,X,le,xe;for(const oe of L.entities){if(L.previewScreenshots.length+L.previewLibraryScenarios.length>=3)break;const Ce=((G=(J=oe.analyses)==null?void 0:J[0])==null?void 0:G.scenarios)||[];if(oe.entityType==="library"){const Re=Ce.find(je=>{var De,Le;return((De=je.metadata)==null?void 0:De.executionResult)||((Le=je.metadata)==null?void 0:Le.error)});Re&&L.previewLibraryScenarios.push({scenario:Re,entitySha:oe.sha})}else{const Re=Ce.find(je=>{var De,Le;return(Le=(De=je.metadata)==null?void 0:De.screenshotPaths)==null?void 0:Le[0]});if(Re){const je=(le=(X=Re.metadata)==null?void 0:X.screenshotPaths)==null?void 0:le[0],De=!!((xe=Re.metadata)!=null&&xe.error);je&&!L.previewScreenshots.includes(je)&&(L.previewScreenshots.push(je),L.previewScreenshotErrors.push(De))}}}});const z=Array.from(j.values());return z.sort((L,J)=>{if(o==="analyzed"){const le=Math.max(...L.entities.filter(oe=>{var me,Ce;return(Ce=(me=oe.analyses)==null?void 0:me[0])==null?void 0:Ce.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0),xe=Math.max(...J.entities.filter(oe=>{var me,Ce;return(Ce=(me=oe.analyses)==null?void 0:me[0])==null?void 0:Ce.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0);return T==="desc"?xe-le:le-xe}if(L.uncommittedCount>0&&J.uncommittedCount===0)return-1;if(L.uncommittedCount===0&&J.uncommittedCount>0)return 1;const G=L.lastUpdated?new Date(L.lastUpdated).getTime():0,X=J.lastUpdated?new Date(J.lastUpdated).getTime():0;return T==="desc"?X-G:G-X}),z},[$,o,T,i,c]),R=ne(()=>{let j=I;if(C!=="all"&&(j=j.filter(q=>q.state===C)),S.trim()){const q=S.toLowerCase();j=j.filter(V=>V.filePath.toLowerCase().includes(q))}return j},[I,S,C]),Y=(t-1)*r,H=Y+r,W=R.slice(Y,H),B=Math.ceil(R.length/r),D=j=>{w(q=>{const V=new Set(q);return V.has(j)?V.delete(j):V.add(j),V})},O=()=>{P(j=>j==="desc"?"asc":"desc")};return d("div",{children:[d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative w-[130px]",children:[d("select",{value:_,onChange:j=>{const q=j.target.value,V=new URLSearchParams(x);q==="all"?V.delete("entityType"):V.set("entityType",q),V.set("page","1"),v(V)},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(lt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"relative w-[130px]",children:[d("select",{value:C,onChange:j=>A(j.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(lt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Vn,{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:S,onChange:j=>E(j.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&&h!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:R.length})," ",R.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:R.reduce((j,q)=>j+q.totalCount,0)})," ",R.reduce((j,q)=>j+q.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?d("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[R.filter(j=>j.uncommittedCount>0).length," ","uncommitted"," ",R.filter(j=>j.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):d("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),W.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{w(new Set(W.map(j=>j.filePath))),N(!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(ji,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{w(new Set),N(!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(Mi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Wo,{showActions:!0,sortOrder:T,onSortChange:O}),n("div",{className:"flex flex-col gap-[3px]",children:W.map(j=>{const q=b.has(j.filePath),U=j.entities.filter(J=>(J.entityType==="visual"||J.entityType==="library")&&(ot(J,(i==null?void 0:i.jobs)||[])==="not-analyzed"||ot(J,(i==null?void 0:i.jobs)||[])==="out-of-date"||ot(J,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,Z=J=>{var G;return((G=s==null?void 0:s.currentEntityShas)==null?void 0:G.includes(J))||!1},z=J=>{var G;return l!=null&&l(J)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(X=>{var le;return(le=X.entityShas)==null?void 0:le.includes(J.sha)}))||!1},L=J=>{p==null||p(J)};return n(Jo,{filePath:j.filePath,isExpanded:q,onToggle:()=>D(j.filePath),simulationPreviews:n(Ho,{entities:j.entities,maxPreviews:1}),entityCount:j.totalCount,state:j.state,lastModified:j.lastUpdated,uncommittedCount:j.uncommittedCount,isUncommitted:j.uncommittedCount>0,actionButton:U?n("button",{onClick:J=>{J.stopPropagation();const G=j.entities.filter(X=>(X.entityType==="visual"||X.entityType==="library")&&(ot(X,(i==null?void 0:i.jobs)||[])==="not-analyzed"||ot(X,(i==null?void 0:i.jobs)||[])==="out-of-date"||ot(X,(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:j.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:j.entities.sort((J,G)=>{var me,Ce,Re,je;const X=!((me=J.metadata)!=null&&me.notExported)&&!((Ce=J.metadata)!=null&&Ce.namedExport),le=!((Re=G.metadata)!=null&&Re.notExported)&&!((je=G.metadata)!=null&&je.namedExport);if(X&&!le)return-1;if(!X&&le)return 1;const xe=J.entityType==="visual"||J.entityType==="library",oe=G.entityType==="visual"||G.entityType==="library";return xe&&!oe?-1:!xe&&oe?1:J.name.localeCompare(G.name)}).map(J=>n(Vo,{entity:J,isActivelyAnalyzing:Z(J.sha),isQueued:z(J),onGenerateSimulation:L},J.sha))},j.filePath)})}),B>1&&d("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),d("span",{children:["Page ",t," of ",B]}),t<B&&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 hw=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function fw({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),o=r.searchParams.get("filter")||null,a=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[c,p]=await Promise.all([cn(),Nn()]);return Q({entities:c,currentCommit:p,page:s,filter:o,entityType:a,queueState:l})}catch(r){return console.error("Failed to load entities:",r),Q({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const gw=We(function(){var S,E,k;const{entities:t,currentCommit:r,page:s,filter:o,entityType:a,queueState:i,error:l}=Ve();ht();const[c,p]=vn(),[u,m]=M(!1);gt({source:"files-page"});const{handleGenerateSimulation:h,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=vc((E=(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun)==null?void 0:E.currentEntityShas,i),x=t||[],v=ne(()=>{const N=new Set([]);for(const C of x)N.add(C.filePath??"No File Path");return Array.from(N)},[x]),b=ne(()=>{let N=x;return u&&(N=N.filter(C=>{var A;return(A=C.metadata)==null?void 0:A.isUncommitted})),N.sort((C,A)=>{var T,P,_,$,I,R;return(T=C.metadata)!=null&&T.isUncommitted&&!((P=A.metadata)!=null&&P.isUncommitted)?-1:!((_=C.metadata)!=null&&_.isUncommitted)&&(($=A.metadata)!=null&&$.isUncommitted)?1:new Date(((I=A.metadata)==null?void 0:I.editedAt)||0).getTime()-new Date(((R=C.metadata)==null?void 0:R.editedAt)||0).getTime()})},[x,u]),w=ne(()=>{var C;const N=new Set([]);for(const A of x)(C=A.metadata)!=null&&C.isUncommitted&&N.add(A.filePath??"No File Path");return Array.from(N)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:d("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),d("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(mw,{entities:b,page:s,itemsPerPage:50,currentRun:(k=r==null?void 0:r.metadata)==null?void 0:k.currentRun,filter:o,entityType:a,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:h,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:w.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),yw=Object.freeze(Object.defineProperty({__proto__:null,default:gw,loader:fw,meta:hw},Symbol.toStringTag,{value:"Module"})),xw=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function bw({request:e}){var t;try{const r=await Te();if(!r)return Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await $e(r),o=pe()||process.cwd(),a=Xl(o)||"";let i="";try{const c=await Hr();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const p=c.webapps.map(u=>u.framework).filter(Boolean);p.length>0&&(i=p.join(", "))}}catch{}const l=rc(r);return Q({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:a,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function vw({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return Q({success:!1,error:"Missing feature name"},{status:400});const o=await Te();return o?(r==="clearAccess"?await xn({projectSlug:o,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await xn({projectSlug:o,metadataUpdate:{labs:{[r]:s}}}),Q({success:!0,error:null})):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),Q({success:!1,error:"Failed to save labs configuration"},{status:500})}}const ww=[{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}],Si="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",Nw=[{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 Cw({onClose:e}){const t=be(null),r=be(0);return te(()=>{const s=t.current;if(!s)return;const o=100,a=2e3,i=500;let l=null,c=!1;const p=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const u=Date.now()-r.current,m=s.scrollTop>o,h=u>a;m&&h&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",p,{passive:!0}),()=>{s.removeEventListener("scroll",p),l&&clearInterval(l)}},[]),d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Si}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:d("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),d("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Si,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Sw({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const o=(i=s.data)==null?void 0:i.error,a=(l=s.data)==null?void 0:l.success;return d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:c=>{c.target===c.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),d(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:c=>r(c.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),o&&n("p",{className:"text-red-600 text-sm mt-2",children:o}),a&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const kw=We(function(){const{labs:t,unlockCode:r,error:s}=Ve(),o=Oe(),a=Oe(),i=Oe(),[l,c]=M(""),[p,u]=M(!1),[m,h]=M(!1);gt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?d("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:ww.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=a.state==="submitting"&&((v=a.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:d("div",{className:"flex items-center justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),d(a.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:d("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),d("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),d(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):d("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[p&&n(Cw,{onClose:()=>u(!1)}),m&&n(Sw,{onClose:()=>h(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:o}),d("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>h(!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"})]})]}),d("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),d("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>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"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:Nw.map(y=>d("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[d("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",d("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:d("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>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."})]})})]})}),Ew=Object.freeze(Object.defineProperty({__proto__:null,action:vw,default:kw,loader:bw,meta:xw},Symbol.toStringTag,{value:"Module"}));function Aw(e,t,r){const[s,o]=M(()=>new Set),[a,i]=M(()=>new Set),l=be([]),c=be([]);return te(()=>{(t.length!==l.current.length||t.some((g,x)=>g!==l.current[x]))&&(l.current=t,o(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),te(()=>{(r.length!==c.current.length||r.some((g,x)=>g!==c.current[x]))&&(c.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:a,setExpandedUncommitted:o,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:()=>{o(new Set(t))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Pw(e,t,r){const[s,o]=M(null),[a,i]=M(null),l=Oe();te(()=>{var m,h;((m=l.data)==null?void 0:m.oldContent)!==void 0&&((h=l.data)==null?void 0:h.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=m=>{o({type:"file",path:m}),i(null);const h=new FormData;h.append("actionType","getDiff"),h.append("filePath",m),h.append("diffType","branch"),h.append("baseBranch",e),h.append("currentBranch",t||""),l.submit(h,{method:"post"})},p=(m,h)=>{o({type:"entity",path:m,entitySha:h}),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",h),l.submit(f,{method:"post"})},u=()=>{o(null),i(null)};return{diffView:s,diffContent:a,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:p,handleCloseDiff:u}}function _w({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:o}){var p;const[a,i]=M(!1),[l,c]=M(!1);return te(()=>{c(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:d("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[d("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[d("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&d("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((p=s.find(u=>u.sha===e.entitySha))==null?void 0:p.name)||e.entitySha]})]}),d("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!a),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:a?"Show changes only":"Show full file",children:a?"Show Changes Only":"Show Full File"}),n("button",{onClick:o,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Bd,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!a,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:o,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function jw({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:o,expandedFiles:a,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:p,onBranchChange:u,onGenerateSimulation:m,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([w,{entities:S}])=>{const E=S.filter(k=>i(k.sha)||l(k)).map(k=>k.sha);return E.length>0?[{entityShas:E}]:[]}),v=w=>{const S=w.map(E=>ot(E,x));return S.includes("analyzing")||S.includes("queued")?"analyzing":S.includes("out-of-date")?"out-of-date":S.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ne(()=>[...e].sort((w,S)=>{const E=w[1].entities.reduce((A,T)=>{var _;const P=((_=T.metadata)==null?void 0:_.editedAt)||T.updatedAt;return P?A?new Date(P)>new Date(A)?P:A:P:A},null),k=S[1].entities.reduce((A,T)=>{var _;const P=((_=T.metadata)==null?void 0:_.editedAt)||T.updatedAt;return P?A?new Date(P)>new Date(A)?P:A:P:A},null);if(!E&&!k)return 0;if(!E)return 1;if(!k)return-1;const N=new Date(E).getTime(),C=new Date(k).getTime();return c==="desc"?C-N:N-C}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(Wo,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:S,entities:E,isUncommitted:k}])=>{const N=a.has(w),C=v(E),A=E.reduce(($,I)=>{var Y;const R=((Y=I.metadata)==null?void 0:Y.editedAt)||I.updatedAt;return R?$?new Date(R)>new Date($)?R:$:R:$},null),P=E.filter($=>$.entityType==="visual"||$.entityType==="library").length===0;let _;return P?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):C==="analyzing"?_=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):C==="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"}):C==="out-of-date"?_=n("button",{onClick:$=>{$.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>m(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):C==="not-analyzed"&&(_=n("button",{onClick:$=>{$.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>m(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Jo,{filePath:w,isExpanded:N,onToggle:()=>p(w),fileStatus:S,isUncommitted:k,simulationPreviews:n(Ho,{entities:E,maxPreviews:1}),entityCount:E.length,state:C,lastModified:A,isNotAnalyzable:P,actionButton:_,children:E.sort(($,I)=>{const R=$.entityType==="visual"||$.entityType==="library",Y=I.entityType==="visual"||I.entityType==="library";return R&&!Y?-1:!R&&Y?1:0}).map($=>n(Vo,{entity:$,isActivelyAnalyzing:i($.sha),isQueued:l($),onGenerateSimulation:m},$.sha))},w)})})]}):d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Mw({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:o,projectSlug:a,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:p,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=ne(()=>{const w=[];return e.forEach(([S,{editedEntities:E}])=>{const k=E.filter(N=>s(N.sha)||o(N)).map(N=>N.sha);k.length>0&&w.push({entityShas:k})}),w},[e,s,o]),v=ne(()=>{const w=new Map;return e.forEach(([S,{editedEntities:E}])=>{const k=E.map(T=>ot(T,x));let N;k.includes("analyzing")||k.includes("queued")?N="analyzing":k.includes("out-of-date")?N="out-of-date":k.includes("not-analyzed")?N="not-analyzed":N="up-to-date";const C=E.reduce((T,P)=>{var $;const _=(($=P.metadata)==null?void 0:$.editedAt)||P.updatedAt;return _&&(!T||new Date(_)>new Date(T))?_:T},null),A=E.filter(T=>T.entityType==="visual"||T.entityType==="library").length;w.set(S,{state:N,lastModified:C,analyzableCount:A})}),w},[e,x]),b=ne(()=>[...e].sort((w,S)=>{const E=v.get(w[0]),k=v.get(S[0]),N=E==null?void 0:E.lastModified,C=k==null?void 0:k.lastModified;if(!N&&!C)return 0;if(!N)return 1;if(!C)return-1;const A=new Date(N).getTime(),T=new Date(C).getTime();return c==="desc"?T-A:A-T}),[e,v,c]);return e.length===0?d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):d("div",{children:[n(Wo,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:S,editedEntities:E}])=>{const k=r.has(w),N=v.get(w),{state:C,lastModified:A,analyzableCount:T}=N,P=T===0;let _;return P?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):C==="analyzing"?_=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):C==="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"}):C==="out-of-date"?_=n("button",{onClick:$=>{$.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!s(I.sha)&&!o(I)).forEach(I=>m(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):C==="not-analyzed"&&(_=n("button",{onClick:$=>{$.stopPropagation(),E.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!s(I.sha)&&!o(I)).forEach(I=>m(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Jo,{filePath:w,isExpanded:k,onToggle:()=>p(w),fileStatus:S,simulationPreviews:n(Ho,{entities:E,maxPreviews:1}),entityCount:E.length,state:C,lastModified:A,isNotAnalyzable:P,isUncommitted:!0,actionButton:_,children:E.sort(($,I)=>{const R=$.entityType==="visual"||$.entityType==="library",Y=I.entityType==="visual"||I.entityType==="library";return R&&!Y?-1:!R&&Y?1:0}).map($=>n(Vo,{entity:$,isActivelyAnalyzing:s($.sha),isQueued:o($),onGenerateSimulation:m},$.sha))},w)})})]})}function Tw({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:d("nav",{className:"flex gap-8 items-center",children:[d("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),d("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const $w=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Rw({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),o=t.get("diffType"),a=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let c;return o==="branch"?c=gr(s,a,i):c=Yh(s),Q({...c,entitySha:l})}return Q({error:"Unknown action"},{status:400})}async function Iw({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),o=r.searchParams.get("viewBranch"),a=t.analysisQueue,i=a?a.getState():{paused:!1,jobs:[]},[l,c,p]=await Promise.all([cn(),Nn(),Te()]),u=kn(),m=Lh(),h=Fh(),f=zh(),y=o||m,g=s||h;let x=[];return y&&y!==g&&(x=Il(g,y)),Q({entities:l||[],gitStatus:u,currentBranch:y,actualCurrentBranch:m,defaultBranch:h,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:c,projectSlug:p,queueState:i})}catch(r){return console.error("Failed to load git data:",r),Q({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 Dw=We(function(){var Se,ct;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:o,defaultBranch:a,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:p,projectSlug:u,queueState:m}=Ve();gt({source:"git-page"});const[h,f]=vn(),[y,g]=M(null),[x,v]=M("desc"),[b,w]=M("branch"),S=h.get("expanded")==="true",E=()=>{v(he=>he==="desc"?"asc":"desc")},k=Oe(),N=k.data;te(()=>{s&&l&&s!==l&&k.state==="idle"&&!N&&k.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,k,N]);const C=ne(()=>{const he=hc(r,t);return Array.from(he.entries()).sort((Be,Je)=>Be[0].localeCompare(Je[0]))},[r,t]),A=ne(()=>{const he=av(c,t,N);return Array.from(he.entries()).sort((Be,Je)=>Be[0].localeCompare(Je[0]))},[c,t,N]),T=ne(()=>iv(r,t),[r,t]),P=ne(()=>b==="uncommitted"?C:A,[b,C,A]),_=ne(()=>P.map(([he])=>he),[P]),{expandedUncommitted:$,setExpandedUncommitted:I,toggleFile:R,expandAllUncommitted:Y,collapseAllUncommitted:H}=Aw(S,_,[]),{diffView:W,diffContent:B,isLoading:D,handleShowFileDiff:O,handleCloseDiff:j}=Pw(l,s),q=(Se=p==null?void 0:p.metadata)==null?void 0:Se.currentRun,V=new Set((q==null?void 0:q.currentEntityShas)||[]),U=new Set(m.jobs.flatMap(he=>he.entityShas||[])),Z=new Set(((ct=m.currentlyExecuting)==null?void 0:ct.entityShas)||[]),{isAnalyzing:z,handleGenerateSimulation:L,handleGenerateAllSimulations:J,isEntityBeingAnalyzed:G,isEntityPending:X}=vc(q==null?void 0:q.currentEntityShas,m),le=he=>X(he)||U.has(he.sha)||Z.has(he.sha),xe=he=>{he===(o||s)?h.delete("viewBranch"):h.set("viewBranch",he),f(h)},oe=he=>{he===a?h.delete("compare"):h.set("compare",he),f(h)},me=()=>{const Be=P.flatMap(([Je,yt])=>yt.editedEntities||yt.entities||[]).filter(Je=>!V.has(Je.sha)&&!U.has(Je.sha)&&!Z.has(Je.sha)&&!X(Je));J(Be)},Ce=C.length,Re=A.length,je=P.flatMap(([he,Be])=>Be.editedEntities||Be.entities||[]),De=je.filter(he=>he.entityType==="visual"||he.entityType==="library"),Le=De.length>0&&De.every(he=>V.has(he.sha)),Ee=De.length>0&&!Le&&De.every(he=>U.has(he.sha)||Z.has(he.sha)),re=z||Le||Ee,ye=Le?"Analyzing...":Ee?"Queued...":z?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),d("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Tw,{activeTab:b,onTabChange:w,uncommittedCount:Ce,branchCount:Re})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===a?d("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:a}),"."]}):d("div",{className:"flex gap-6 items-center",children:[d("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?d("div",{className:"relative w-50",children:[n("select",{value:s,onChange:he=>xe(he.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(he=>n("option",{value:he,children:he},he))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),d("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),d("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:he=>oe(he.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(he=>he!==s).map(he=>n("option",{value:he,children:he},he))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:d("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:P.length})," ","modified ",P.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:je.length})," ",je.length===1?"entity":"entities"]})]}),P.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:Y,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(ji,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:H,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(Mi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(jw,{files:A,currentBranch:s,defaultBranch:a,baseBranch:l,allBranches:i,expandedFiles:$,isEntityBeingAnalyzed:G,isEntityQueued:le,sortOrder:x,onToggleFile:he=>R(he,$,I),onBranchChange:oe,onGenerateSimulation:L,onSortChange:E,onAnalyzeAll:me,analyzeAllDisabled:re,analyzeAllText:ye}),b==="uncommitted"&&n(Mw,{files:C,entityImpactMap:T,expandedFiles:$,isEntityBeingAnalyzed:G,isEntityQueued:le,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:he=>R(he,$,I),onShowFileDiff:O,onGenerateSimulation:L,onSortChange:E,onAnalyzeAll:me,analyzeAllDisabled:re,analyzeAllText:ye})]}),W&&n(_w,{diffView:W,diffContent:B,isLoading:D,entities:t,onClose:j}),y&&u&&n(Ft,{projectSlug:u,onClose:()=>g(null)})]})})}),Ow=Object.freeze(Object.defineProperty({__proto__:null,action:Rw,default:Dw,loader:Iw,meta:$w},Symbol.toStringTag,{value:"Module"})),$N={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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/root-B_X8HS1x.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-BzHcG7SE.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-DaAZ_H2w.js","/assets/createLucideIcon-CC6AbExI.js","/assets/book-open-BYOypzCa.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-C_Pmso5S.js","/assets/circle-check-BVMi9VA5.js","/assets/CopyButton-BPXZwM4t.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-D5rYBT5x.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/editorPreview-B7ztwLut.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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-Bni3iiUj.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CC6AbExI.js","/assets/terminal-Br7MOqts.js","/assets/search-Di64LWVb.js","/assets/chevron-down-C_Pmso5S.js","/assets/book-open-BYOypzCa.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BcY3q6nt.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-DaAZ_H2w.js","/assets/pause-f5-1lKBt.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha._-BF4oLwaE.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-0DY_NKil.js","/assets/createLucideIcon-CC6AbExI.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/CopyButton-BPXZwM4t.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/ReportIssueModal-BzHcG7SE.js","/assets/circle-check-BVMi9VA5.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/simulations-DWT-CvLy.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/loader-circle-DaAZ_H2w.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/dev.empty-Csi0_PMl.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-0DY_NKil.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.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-BzHcG7SE.js","/assets/createLucideIcon-CC6AbExI.js","/assets/circle-check-BVMi9VA5.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/settings-0OrEMU6J.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-BPXZwM4t.js","/assets/copy-n2FB0_Sw.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/_index-DLxKhri3.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-CQIG2qda.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CC6AbExI.js","/assets/circle-check-BVMi9VA5.js","/assets/loader-circle-DaAZ_H2w.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor-BuT_Huj0.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/editorPreview-B7ztwLut.js","/assets/CopyButton-BPXZwM4t.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/copy-n2FB0_Sw.js","/assets/createLucideIcon-CC6AbExI.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/memory-Bl2rpw8u.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CC6AbExI.js","/assets/terminal-Br7MOqts.js","/assets/copy-n2FB0_Sw.js","/assets/CopyButton-BPXZwM4t.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/pause-f5-1lKBt.js","/assets/book-open-BYOypzCa.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/files-BZrlFE1F.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-BcgbViKV.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/createLucideIcon-CC6AbExI.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-BLdiCuG-.js","/assets/EntityTypeIcon-CQIG2qda.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,hasDefaultExport:!0,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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/git-DdZcvjGh.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-BcgbViKV.js","/assets/LogViewer-ceAyBX-H.js","/assets/index-yHOVb4rc.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CC6AbExI.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-BLdiCuG-.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-b0f1372e.js",version:"b0f1372e",sri:void 0},RN="build/client",IN="/",DN={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},ON=!0,LN=!1,FN=[],zN={mode:"lazy",manifestPath:"/__manifest"},BN="/",YN={module:Ud},UN={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:bm},"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:Sm},"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:Rm},"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:Dm},"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:sh},"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:Xh},"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:af},"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:df},"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:pf},"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:hf},"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:gf},"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:xg},"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:Mg},"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:$g},"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:Ig},"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:zg},"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:Yg},"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:Jg},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,module:Vg},"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:Qg},"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:s0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:a0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:y0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:w0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:I0},"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:F0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Y0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:W0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:H0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:q0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Z0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:ey},"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:ry},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:hy},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:gy},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:Sy},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:_y},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:$y},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:Oy},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Fy},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:tx},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:rx},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:dx},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:px},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:xx},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:vx},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:jx},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:$x},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:Ix},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:Fx},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Bx},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:Hx},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:fb},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:xb},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:kb},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Ab},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:_b},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Ub},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Hb},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:qb},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:nv},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:sv},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:mv},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:Uv},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:uw},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:yw},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Ew},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Ow}},WN=!1;export{Zu as A,qu as B,Me as C,wu as D,Nu as E,ln as F,cu as G,zi as H,Bi as I,pu as J,Yi as K,fu as L,yu as M,RN as N,IN as O,iu as P,DN as Q,ON as R,kr as S,LN as T,FN as U,zN as V,BN as W,YN as X,UN as Y,WN as Z,$N as _,nu as a,yn as b,sn as c,_t as d,Kn as e,fo as f,go as g,Fi as h,eu as i,Tu as j,$u as k,zt as l,jt as m,Ji as n,Bu as o,Ar as p,et as q,Hi as r,Vi as s,Hu as t,Lt as u,Gi as v,wn as w,xn as x,Ca as y,tp as z};
|