@codeyam/codeyam-cli 0.1.0-staging.1 → 0.1.0-staging.28f73cf

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.
Files changed (440) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +8 -7
  4. package/analyzer-template/packages/ai/index.ts +2 -1
  5. package/analyzer-template/packages/ai/package.json +2 -2
  6. package/analyzer-template/packages/ai/scripts/ai-test-matrix.mjs +424 -0
  7. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +24 -0
  8. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +6 -16
  9. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +197 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +28 -2
  11. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +127 -4
  12. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +1 -3
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1821 -542
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.ts +138 -0
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +1 -1
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +139 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/DebugTracer.ts +224 -0
  18. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/PathManager.ts +203 -0
  19. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/README.md +294 -0
  20. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +161 -0
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.ts +235 -0
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +14 -6
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/selectBestValue.ts +70 -0
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.ts +113 -0
  25. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +36 -0
  26. package/analyzer-template/packages/ai/src/lib/generateChangesEntityDocumentation.ts +20 -2
  27. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +51 -107
  28. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +56 -160
  29. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +79 -265
  30. package/analyzer-template/packages/ai/src/lib/generateEntityDocumentation.ts +16 -2
  31. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +53 -176
  32. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +53 -154
  33. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +84 -254
  34. package/analyzer-template/packages/ai/src/lib/generateStatementAnalysis.ts +48 -71
  35. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +27 -6
  36. package/analyzer-template/packages/ai/src/lib/getLLMCallStats.ts +0 -14
  37. package/analyzer-template/packages/ai/src/lib/modelInfo.ts +15 -0
  38. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +42 -4
  39. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.ts +8 -33
  40. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +54 -62
  41. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +93 -109
  42. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.ts +8 -27
  43. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +33 -38
  44. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +30 -30
  45. package/analyzer-template/packages/ai/src/lib/types/index.ts +2 -0
  46. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +39 -0
  47. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +52 -6
  48. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +2 -1
  49. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +238 -0
  50. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.ts +25 -0
  51. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/index.ts +2 -0
  52. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +8 -10
  53. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -1
  54. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +8 -6
  55. package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +5 -13
  56. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +34 -15
  57. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +17 -3
  58. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +35 -16
  59. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +7 -1
  60. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +9 -1
  61. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +6 -1
  62. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +9 -1
  63. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +15 -7
  64. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts +23 -0
  65. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts.map +1 -0
  66. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js +30 -0
  67. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js.map +1 -0
  68. package/analyzer-template/packages/aws/package.json +5 -4
  69. package/analyzer-template/packages/aws/s3/index.ts +4 -0
  70. package/analyzer-template/packages/aws/src/lib/s3/getPresignedUrl.ts +62 -0
  71. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +28 -21
  72. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.ts +18 -11
  73. package/analyzer-template/packages/generate/src/lib/scenarioComponent.ts +6 -3
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  75. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
  76. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  77. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.d.ts.map +1 -1
  78. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
  79. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
  80. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.d.ts.map +1 -1
  81. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js +5 -3
  82. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js.map +1 -1
  83. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts +2 -0
  84. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts.map +1 -1
  85. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js +3 -0
  86. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js.map +1 -1
  87. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts +2 -0
  88. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts.map +1 -1
  89. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts +37 -0
  90. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -0
  91. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  92. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  93. package/analyzer-template/packages/github/dist/utils/index.d.ts +2 -0
  94. package/analyzer-template/packages/github/dist/utils/index.d.ts.map +1 -1
  95. package/analyzer-template/packages/github/dist/utils/index.js +2 -0
  96. package/analyzer-template/packages/github/dist/utils/index.js.map +1 -1
  97. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts +25 -0
  98. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  99. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js +40 -0
  100. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js.map +1 -0
  101. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
  102. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  103. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  104. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  105. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  106. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  107. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
  108. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  109. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  110. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  111. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  112. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  113. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
  114. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
  115. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  116. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  117. package/analyzer-template/packages/supabase/src/lib/kysely/db.ts +6 -0
  118. package/analyzer-template/packages/supabase/src/lib/kysely/tableRelations.ts +3 -0
  119. package/analyzer-template/packages/supabase/src/lib/kysely/tables/debugReportsTable.ts +61 -0
  120. package/analyzer-template/packages/ui-components/src/scenario-editor/components/DataItemEditor.tsx +1 -1
  121. package/analyzer-template/packages/utils/dist/utils/index.d.ts +2 -0
  122. package/analyzer-template/packages/utils/dist/utils/index.d.ts.map +1 -1
  123. package/analyzer-template/packages/utils/dist/utils/index.js +2 -0
  124. package/analyzer-template/packages/utils/dist/utils/index.js.map +1 -1
  125. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts +25 -0
  126. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  127. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js +40 -0
  128. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js.map +1 -0
  129. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
  130. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  131. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  132. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  133. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  134. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  135. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
  136. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  137. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  138. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  139. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  140. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  141. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
  142. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
  143. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  144. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  145. package/analyzer-template/packages/utils/index.ts +2 -0
  146. package/analyzer-template/packages/utils/src/lib/Semaphore.ts +42 -0
  147. package/analyzer-template/packages/utils/src/lib/frameworks/getNextRoutePath.ts +8 -3
  148. package/analyzer-template/packages/utils/src/lib/frameworks/getRemixRoutePath.ts +2 -1
  149. package/analyzer-template/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.ts +2 -1
  150. package/analyzer-template/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.ts +1 -0
  151. package/analyzer-template/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.ts +33 -0
  152. package/analyzer-template/project/constructMockCode.ts +170 -6
  153. package/analyzer-template/project/reconcileMockDataKeys.ts +13 -0
  154. package/analyzer-template/project/start.ts +1 -11
  155. package/analyzer-template/project/startScenarioCapture.ts +24 -0
  156. package/analyzer-template/project/trackGeneratedFiles.ts +41 -0
  157. package/analyzer-template/project/writeMockDataTsx.ts +125 -4
  158. package/analyzer-template/project/writeScenarioComponents.ts +199 -45
  159. package/analyzer-template/project/writeUniversalMocks.ts +72 -10
  160. package/background/src/lib/virtualized/project/constructMockCode.js +158 -7
  161. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  162. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +12 -0
  163. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  164. package/background/src/lib/virtualized/project/start.js +1 -8
  165. package/background/src/lib/virtualized/project/start.js.map +1 -1
  166. package/background/src/lib/virtualized/project/startScenarioCapture.js +18 -0
  167. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  168. package/background/src/lib/virtualized/project/trackGeneratedFiles.js +30 -0
  169. package/background/src/lib/virtualized/project/trackGeneratedFiles.js.map +1 -0
  170. package/background/src/lib/virtualized/project/writeMockDataTsx.js +95 -3
  171. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  172. package/background/src/lib/virtualized/project/writeScenarioComponents.js +144 -28
  173. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  174. package/background/src/lib/virtualized/project/writeUniversalMocks.js +59 -9
  175. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  176. package/codeyam-cli/scripts/apply-setup.js +288 -0
  177. package/codeyam-cli/scripts/apply-setup.js.map +1 -0
  178. package/codeyam-cli/scripts/extract-setup.js +130 -0
  179. package/codeyam-cli/scripts/extract-setup.js.map +1 -0
  180. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +238 -0
  181. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +1 -0
  182. package/codeyam-cli/src/cli.js +6 -0
  183. package/codeyam-cli/src/cli.js.map +1 -1
  184. package/codeyam-cli/src/codeyam-cli.js +0 -0
  185. package/codeyam-cli/src/commands/debug.js +221 -0
  186. package/codeyam-cli/src/commands/debug.js.map +1 -0
  187. package/codeyam-cli/src/commands/init.js +4 -23
  188. package/codeyam-cli/src/commands/init.js.map +1 -1
  189. package/codeyam-cli/src/commands/report.js +102 -0
  190. package/codeyam-cli/src/commands/report.js.map +1 -0
  191. package/codeyam-cli/src/commands/setup-sandbox.js +164 -0
  192. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -0
  193. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js +6 -6
  194. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js.map +1 -1
  195. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +8 -0
  196. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  197. package/codeyam-cli/src/utils/analysisRunner.js +4 -3
  198. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  199. package/codeyam-cli/src/utils/analyzer.js +30 -0
  200. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  201. package/codeyam-cli/src/utils/backgroundServer.js +25 -5
  202. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  203. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js +2 -2
  204. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js.map +1 -1
  205. package/codeyam-cli/src/utils/fileWatcher.js +75 -5
  206. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  207. package/codeyam-cli/src/utils/generateReport.js +219 -0
  208. package/codeyam-cli/src/utils/generateReport.js.map +1 -0
  209. package/codeyam-cli/src/utils/install-skills.js +7 -0
  210. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  211. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js +1 -0
  212. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js.map +1 -1
  213. package/codeyam-cli/src/utils/queue/job.js +8 -3
  214. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  215. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +4 -0
  216. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  217. package/codeyam-cli/src/utils/webappDetection.js +2 -1
  218. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  219. package/codeyam-cli/src/webserver/app/lib/database.js +63 -2
  220. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  221. package/codeyam-cli/src/webserver/backgroundServer.js +15 -35
  222. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  223. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-D5ZHFomX.js +1 -0
  224. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-Dh-FldQK.js → InteractivePreview-XDSzQLOY.js} +3 -3
  225. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-BYVx9KFp.js +3 -0
  226. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-Dp6DC845.js → LogViewer-CRcT5fOZ.js} +1 -1
  227. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BORLgi0X.js +1 -0
  228. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Bual6h18.js +1 -0
  229. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bi-YUMa-.js +6 -0
  230. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-4D2vLLJz.js +5 -0
  231. package/codeyam-cli/src/webserver/build/client/assets/_index-BC200mfN.js +1 -0
  232. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CxvZPkCv.js +10 -0
  233. package/codeyam-cli/src/webserver/build/client/assets/api.generate-report-l0sNRNKZ.js +1 -0
  234. package/codeyam-cli/src/webserver/build/client/assets/{chart-column-B2I7jQx2.js → chart-column-B8fb6wnw.js} +1 -1
  235. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-De6i8FUT.js +26 -0
  236. package/codeyam-cli/src/webserver/build/client/assets/{circle-alert-GwwOAbhw.js → circle-alert-IdsgAK39.js} +1 -1
  237. package/codeyam-cli/src/webserver/build/client/assets/circle-check-BACUUf75.js +1 -0
  238. package/codeyam-cli/src/webserver/build/client/assets/clock-vWeoCemX.js +1 -0
  239. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CS7XDrKv.js +1 -0
  240. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DIOEw_3i.js +1 -0
  241. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-1Z6D0fLM.js → entity._sha._-8Els_3Wb.js} +10 -10
  242. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-C3FZJx1w.js +1 -0
  243. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-YJz_igar.js +5 -0
  244. package/codeyam-cli/src/webserver/build/client/assets/entityStatus-BEqj2qBy.js +1 -0
  245. package/codeyam-cli/src/webserver/build/client/assets/{entityVersioning-DO2gCvXv.js → entityVersioning-Bk_YB1jM.js} +1 -1
  246. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DiP0q291.js +5 -0
  247. package/codeyam-cli/src/webserver/build/client/assets/file-text-LM0mgxXE.js +1 -0
  248. package/codeyam-cli/src/webserver/build/client/assets/files-Dxh9CcaV.js +1 -0
  249. package/codeyam-cli/src/webserver/build/client/assets/git-BXmqrWCH.js +12 -0
  250. package/codeyam-cli/src/webserver/build/client/assets/globals-BGS74ED-.css +1 -0
  251. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +5 -0
  252. package/codeyam-cli/src/webserver/build/client/assets/index-D-zYbzFZ.js +8 -0
  253. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-DN7Vr40D.js → loader-circle-BXPKbHEb.js} +1 -1
  254. package/codeyam-cli/src/webserver/build/client/assets/manifest-1af162d4.js +1 -0
  255. package/codeyam-cli/src/webserver/build/client/assets/root-DB7VgjCY.js +16 -0
  256. package/codeyam-cli/src/webserver/build/client/assets/{settings-MZc4XdmE.js → settings-5zF_GOcS.js} +1 -1
  257. package/codeyam-cli/src/webserver/build/client/assets/settings-Dc4MlMpK.js +1 -0
  258. package/codeyam-cli/src/webserver/build/client/assets/simulations-BQ-02-jB.js +1 -0
  259. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-D7k-ArFa.js +1 -0
  260. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BBlyqxij.js → useLastLogLine-AlhS7g5F.js} +1 -1
  261. package/codeyam-cli/src/webserver/build/client/assets/useToast-Ddo4UQv7.js +1 -0
  262. package/codeyam-cli/src/webserver/build/client/assets/{zap-B4gsLUZQ.js → zap-_jw-9DCp.js} +1 -1
  263. package/codeyam-cli/src/webserver/build/server/assets/index-D4JpXSIO.js +1 -0
  264. package/codeyam-cli/src/webserver/build/server/assets/server-build-vwbN7n65.js +169 -0
  265. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  266. package/codeyam-cli/src/webserver/build-info.json +5 -5
  267. package/codeyam-cli/src/webserver/server.js +1 -1
  268. package/codeyam-cli/src/webserver/server.js.map +1 -1
  269. package/codeyam-cli/templates/codeyam-setup-skill.md +85 -94
  270. package/codeyam-cli/templates/debug-command.md +125 -0
  271. package/package.json +9 -11
  272. package/packages/ai/index.js +1 -2
  273. package/packages/ai/index.js.map +1 -1
  274. package/packages/ai/src/lib/analyzeScope.js +13 -0
  275. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  276. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +6 -15
  277. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  278. package/packages/ai/src/lib/astScopes/methodSemantics.js +134 -0
  279. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  280. package/packages/ai/src/lib/astScopes/paths.js +28 -3
  281. package/packages/ai/src/lib/astScopes/paths.js.map +1 -1
  282. package/packages/ai/src/lib/astScopes/processExpression.js +111 -3
  283. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  284. package/packages/ai/src/lib/checkAllAttributes.js +1 -3
  285. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  286. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1320 -396
  287. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  288. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js +137 -1
  289. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js.map +1 -1
  290. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +1 -1
  291. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  292. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +112 -0
  293. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -0
  294. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js +176 -0
  295. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js.map +1 -0
  296. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js +178 -0
  297. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js.map +1 -0
  298. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +138 -0
  299. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -0
  300. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js +199 -0
  301. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js.map +1 -0
  302. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +14 -6
  303. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  304. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js +62 -0
  305. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js.map +1 -0
  306. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js +90 -0
  307. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js.map +1 -0
  308. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +22 -0
  309. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  310. package/packages/ai/src/lib/generateChangesEntityDocumentation.js +19 -1
  311. package/packages/ai/src/lib/generateChangesEntityDocumentation.js.map +1 -1
  312. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +51 -107
  313. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  314. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +55 -156
  315. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  316. package/packages/ai/src/lib/generateChangesEntityScenarios.js +79 -262
  317. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  318. package/packages/ai/src/lib/generateEntityDocumentation.js +15 -1
  319. package/packages/ai/src/lib/generateEntityDocumentation.js.map +1 -1
  320. package/packages/ai/src/lib/generateEntityKeyAttributes.js +53 -176
  321. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  322. package/packages/ai/src/lib/generateEntityScenarioData.js +52 -152
  323. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  324. package/packages/ai/src/lib/generateEntityScenarios.js +88 -258
  325. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  326. package/packages/ai/src/lib/generateStatementAnalysis.js +46 -71
  327. package/packages/ai/src/lib/generateStatementAnalysis.js.map +1 -1
  328. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +13 -8
  329. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  330. package/packages/ai/src/lib/getLLMCallStats.js +0 -14
  331. package/packages/ai/src/lib/getLLMCallStats.js.map +1 -1
  332. package/packages/ai/src/lib/modelInfo.js +15 -0
  333. package/packages/ai/src/lib/modelInfo.js.map +1 -1
  334. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +36 -3
  335. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  336. package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js +8 -33
  337. package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js.map +1 -1
  338. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +35 -41
  339. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  340. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +59 -72
  341. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  342. package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js +8 -27
  343. package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js.map +1 -1
  344. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +24 -27
  345. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  346. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +21 -22
  347. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  348. package/packages/ai/src/lib/types/index.js +2 -0
  349. package/packages/ai/src/lib/types/index.js.map +1 -1
  350. package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
  351. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  352. package/packages/analyze/src/lib/FileAnalyzer.js +45 -5
  353. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  354. package/packages/analyze/src/lib/asts/nodes/index.js +2 -1
  355. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  356. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +191 -0
  357. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -0
  358. package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js +16 -0
  359. package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js.map +1 -0
  360. package/packages/analyze/src/lib/asts/sourceFiles/index.js +2 -0
  361. package/packages/analyze/src/lib/asts/sourceFiles/index.js.map +1 -1
  362. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +6 -8
  363. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  364. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +5 -1
  365. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  366. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +8 -2
  367. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  368. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +5 -8
  369. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
  370. package/packages/analyze/src/lib/files/analyzeChange.js +21 -9
  371. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  372. package/packages/analyze/src/lib/files/analyzeEntity.js +10 -4
  373. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  374. package/packages/analyze/src/lib/files/analyzeInitial.js +21 -9
  375. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  376. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +6 -1
  377. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  378. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +9 -1
  379. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  380. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +5 -1
  381. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  382. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +9 -1
  383. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  384. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +16 -7
  385. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  386. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
  387. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  388. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
  389. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
  390. package/packages/generate/src/lib/scenarioComponent.js +5 -3
  391. package/packages/generate/src/lib/scenarioComponent.js.map +1 -1
  392. package/packages/supabase/src/lib/kysely/db.js +3 -0
  393. package/packages/supabase/src/lib/kysely/db.js.map +1 -1
  394. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  395. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  396. package/packages/utils/index.js +2 -0
  397. package/packages/utils/index.js.map +1 -1
  398. package/packages/utils/src/lib/Semaphore.js +40 -0
  399. package/packages/utils/src/lib/Semaphore.js.map +1 -0
  400. package/packages/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  401. package/packages/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  402. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  403. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  404. package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  405. package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  406. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  407. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  408. package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  409. package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  410. package/analyzer-template/packages/ai/src/lib/generateEntityDataMap.ts +0 -375
  411. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-GqWwt5wG.js +0 -1
  412. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-p0fuyqGQ.js +0 -3
  413. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-xwuhwsZH.js +0 -1
  414. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bl2IRh55.js +0 -1
  415. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-M2QuSHKC.js +0 -5
  416. package/codeyam-cli/src/webserver/build/client/assets/_index-CAVtep9Q.js +0 -1
  417. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLmzsLsT.js +0 -10
  418. package/codeyam-cli/src/webserver/build/client/assets/components-CAx5ONX_.js +0 -40
  419. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgyOwWip.js +0 -1
  420. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DGy3zrli.js +0 -1
  421. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-ChAdTrrU.js +0 -1
  422. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-D9L7267w.js +0 -5
  423. package/codeyam-cli/src/webserver/build/client/assets/entry.client-C6FRgjPr.js +0 -1
  424. package/codeyam-cli/src/webserver/build/client/assets/files-C3-cQjgv.js +0 -1
  425. package/codeyam-cli/src/webserver/build/client/assets/git-Dp4EB9nv.js +0 -12
  426. package/codeyam-cli/src/webserver/build/client/assets/globals-Da3jt49-.css +0 -1
  427. package/codeyam-cli/src/webserver/build/client/assets/manifest-172a4629.js +0 -1
  428. package/codeyam-cli/src/webserver/build/client/assets/root-COyVTsPq.js +0 -16
  429. package/codeyam-cli/src/webserver/build/client/assets/search-CvyP_1Lo.js +0 -1
  430. package/codeyam-cli/src/webserver/build/client/assets/settings-Hbf8b7J_.js +0 -1
  431. package/codeyam-cli/src/webserver/build/client/assets/simulations-BMBi0VzO.js +0 -1
  432. package/codeyam-cli/src/webserver/build/client/assets/useToast-C_VxoXTh.js +0 -1
  433. package/codeyam-cli/src/webserver/build/client/cy-logo-cli.svg +0 -13
  434. package/codeyam-cli/src/webserver/build/server/assets/index-eAULANMV.js +0 -1
  435. package/codeyam-cli/src/webserver/build/server/assets/server-build-lutv16q5.js +0 -161
  436. package/codeyam-cli/src/webserver/public/cy-logo-cli.svg +0 -13
  437. package/packages/ai/src/lib/generateEntityDataMap.js +0 -335
  438. package/packages/ai/src/lib/generateEntityDataMap.js.map +0 -1
  439. package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js +0 -17
  440. package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js.map +0 -1
@@ -0,0 +1,169 @@
1
+ import{jsx as n,jsxs as c,Fragment as te}from"react/jsx-runtime";import{PassThrough as Ia}from"node:stream";import{createReadableStreamFromReadable as Ra}from"@react-router/node";import{ServerRouter as ja,useFetcher as ue,useLocation as Ir,useNavigate as ct,Link as ee,UNSAFE_withComponentProps as Ie,Meta as $a,Links as Da,ScrollRestoration as La,Scripts as Oa,useLoaderData as De,useRevalidator as dt,Outlet as Fa,data as D,useParams as Rr,useSearchParams as Mn,useActionData as Ya}from"react-router";import{isbot as za}from"isbot";import{renderToPipeableStream as Ba}from"react-dom/server";import{useState as k,useEffect as G,useCallback as Z,createContext as jr,useContext as $r,useRef as fe,useMemo as ne}from"react";import{Settings as ot,CheckCircle2 as Ct,Bug as kn,AlertTriangle as Cn,Loader2 as He,HomeIcon as Ua,GitCommitIcon as tr,File as qa,ActivityIcon as Nn,SettingsIcon as Wa,PanelsTopLeftIcon as Ga,ComponentIcon as Ha,Clock as Wt,FileText as Oe,CheckCircle as Tn,AlertCircle as In,Pause as Dr,Cog as Ka,ListTodo as Va,BarChart3 as Lr,Code as nr,Box as Ja,List as Qa,Tag as Za,Image as nt,Code2 as Or,ChevronDown as Sn,Search as Xa,X as es,ChevronLeft as ts,ChevronRight as rr,FolderOpen as ns,CodeXml as rs,Zap as Fr,Plus as as,Circle as ss}from"lucide-react";import"fetch-retry";import os from"better-sqlite3";import{Pool as is}from"pg";import*as W from"fs";import Ve,{existsSync as ls}from"fs";import*as K from"path";import le from"path";import{OperationNodeTransformer as cs,Kysely as Yr,ParseJSONResultsPlugin as ds,SqliteDialect as us,PostgresDialect as ms,sql as ke}from"kysely";import*as hs from"kysely/helpers/sqlite";import*as ps from"kysely/helpers/postgres";import pe from"typescript";import*as ve from"fs/promises";import ge,{writeFile as fs,readFile as gs}from"fs/promises";import*as ys from"os";import An from"os";import xs from"prompts";import Vt from"chalk";import Rn,{randomUUID as At}from"crypto";import{ResizableBox as bs}from"react-resizable";import vs from"openai";import ws from"p-queue";import ar from"p-retry";import{exec as jn,execSync as Ne,spawn as $n}from"child_process";import{promisify as Dn}from"util";import{DynamoDBClient as sn,PutItemCommand as Cs}from"@aws-sdk/client-dynamodb";import{LRUCache as Ln}from"lru-cache";import"pluralize";import"piscina";import Ns from"json5";import{marshall as Ss}from"@aws-sdk/util-dynamodb";import As from"dotenv";import Es,{EventEmitter as _s}from"events";import{v4 as Ps}from"uuid";import{fileURLToPath as zr}from"url";import{Prism as Ms}from"react-syntax-highlighter";import{vscDarkPlus as ks}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ts}from"node:crypto";import Is from"v8";import Rs from"react-diff-viewer-continued";const Br=5e3;function js(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),m=d&&za(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),Br+1e3);const{pipe:h,abort:p}=Ba(n(ja,{context:a,url:e.url}),{[m](){l=!0;const f=new Ia({final(y){clearTimeout(u),u=void 0,y()}}),g=Ra(f);r.set("Content-Type","text/html"),h(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const $s=Object.freeze(Object.defineProperty({__proto__:null,default:js,streamTimeout:Br},Symbol.toStringTag,{value:"Module"}));function Ds({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=k(!1);G(()=>{i(!0)},[]);const l=Z(()=>{r?.(e)},[r,e]);return c("button",{className:`
2
+ w-full aspect-square p-3 cursor-pointer focus:outline-none
3
+ flex flex-col items-center justify-center gap-1 text-[#626262]
4
+ hover:bg-[#d8d8d8] text-xs font-ibmPlexSans uppercase
5
+ `,onClick:l,children:[n("div",{className:`${t?"bg-primary-100 text-cygray-10":""} w-10 h-10 rounded-lg flex items-center justify-center`,children:o&&a}),n("span",{className:`${t?"text-primary-100":""} whitespace-nowrap`,children:s})]})}const Ls="/assets/cy-logo-cli-C1gnJVOL.svg",Os=[{value:"analysis-failed",label:"Analysis failed or incomplete"},{value:"screenshot-wrong",label:"Screenshot looks wrong"},{value:"app-crashed",label:"App crashed or froze"},{value:"other",label:"Other issue"}];function Fs(e){return e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function On({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=k("other"),[l,d]=k(""),[m,u]=k(a),[h,p]=k(!1),[f,g]=k(null),[y,v]=k(null),b=ue(),x=b.state!=="idle";if(b.data&&!h&&!y){const C=b.data;C.success&&C.reportId?(p(!0),g(C.reportId)):C.error&&v(C.error)}const N=async()=>{v(null);const C=new FormData;if(C.append("issueType",o),C.append("description",l),C.append("email",m),C.append("source",r.source),C.append("entitySha",r.entitySha||""),C.append("scenarioId",r.scenarioId||""),C.append("analysisId",r.analysisId||""),C.append("currentUrl",r.currentUrl),s)try{const A=await(await fetch(s)).blob();C.append("screenshot",A,"screenshot.jpg")}catch(S){console.error("Failed to convert screenshot:",S)}b.submit(C,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},w=()=>{i("other"),d(""),p(!1),g(null),v(null),t()},E=C=>{C.key==="Escape"&&w()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:E,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[x?n("div",{className:"animate-spin",children:n(ot,{size:24,style:{strokeWidth:1.5}})}):h?n(Ct,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(kn,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:w,className:"text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?c("div",{children:[c("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),c("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:w,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-1",children:"Context"}),n("div",{className:"text-sm font-medium text-gray-900",children:Fs(r)})]}),s&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"issue-type",className:"block text-sm font-medium text-gray-700 mb-2",children:"What went wrong?"}),n("select",{id:"issue-type",value:o,onChange:C=>i(C.target.value),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]",children:Os.map(C=>n("option",{value:C.value,children:C.label},C.value))})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"Tell us more (optional)"}),n("textarea",{id:"description",value:l,onChange:C=>d(C.target.value),placeholder:"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"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email (optional, for follow-up)"}),n("input",{id:"email",type:"email",value:m,onChange:C=>u(C.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),c("div",{className:"mb-6 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Cn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),x&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),y&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Cn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:w,disabled:x,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",children:"Cancel"}),n("button",{onClick:()=>{N()},disabled:x,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",children:x?c(te,{children:[n("div",{className:"animate-spin",children:n(ot,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})}):null}function Ys(){const e=Ir(),t=ct(),[r,a]=k(),[s,o]=k(!1),[i,l]=k(!1),[d,m]=k(null),u=ue();G(()=>{u.state==="idle"&&!u.data&&u.load("/api/generate-report")},[u]);const h=u.data?.defaultEmail||"",p={width:"24px",height:"24px",strokeWidth:1.5},f=[{id:"dashboard",icon:n(Ua,{style:p}),link:"/",name:"Dashboard"},{id:"simulations",icon:c("svg",{width:"24",height:"24",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:p,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations"},{id:"git",icon:n(tr,{style:p}),link:"/git",name:"Git"},{id:"files",icon:n(qa,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:n(Nn,{style:p}),link:"/activity",name:"Activity"},{id:"settings",icon:n(Wa,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:n(tr,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Ga,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Ha,{style:p}),link:"/components",name:"Components",hidden:!0}],g=Z(x=>{const N=f.find(w=>w.id===x);N?.link&&t(N.link),a(w=>w===x?void 0:x)},[f,t]);G(()=>{const x={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[N,w]of Object.entries(x))if(w.some(E=>E==="/"?e.pathname==="/":e.pathname.includes(E))){a(N);return}a(void 0)},[e]);const y=async()=>{l(!0);try{const{default:x}=await import("html2canvas-pro"),w=(await x(document.body)).toDataURL("image/jpeg",.8);m(w),o(!0)}catch(x){console.error("Screenshot capture failed:",x),o(!0)}finally{l(!1)}},v=()=>{o(!1),m(null)},b={source:"navbar",currentUrl:e.pathname};return c(te,{children:[c("div",{id:"sidebar",className:"relative w-full h-screen bg-cygray-30 flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{children:n(ee,{to:"/",className:"flex items-center justify-center h-20",children:n("img",{src:Ls,alt:"CodeYam",className:"h-8"})})}),f.filter(x=>!x.hidden).map(x=>n(Ds,{id:x.id,selected:x.id===r,onClick:g,icon:x.icon,name:x.name},`sidebar-button-${x.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>{y()},disabled:i,className:"flex flex-col items-center gap-1 p-2 rounded-lg text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors disabled:opacity-50 disabled:cursor-wait",title:"Report an issue",children:[i?n(He,{style:p,className:"animate-spin"}):n(kn,{style:p}),n("span",{className:"text-[10px] font-medium",children:i?"Capturing...":"Report Issue"})]})})]}),n(On,{isOpen:s,onClose:v,context:b,defaultEmail:h,screenshotDataUrl:d??void 0})]})}const Ur=jr(void 0);function zs({children:e}){const[t,r]=k([]),a=Z((o,i="info",l=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,m])},[]),s=Z(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Ur.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function Fn(){const e=$r(Ur);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Bs({toast:e,onClose:t}){G(()=>{const s=e.duration||5e3;if(s>0){const o=setTimeout(()=>{t(e.id)},s);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Us({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
6
+ @keyframes slideIn {
7
+ from {
8
+ transform: translateX(400px);
9
+ opacity: 0;
10
+ }
11
+ to {
12
+ transform: translateX(0);
13
+ opacity: 1;
14
+ }
15
+ }
16
+ `}),e.map(r=>n(Bs,{toast:r,onClose:t},r.id))]})}function Ue(e,t){const[r,a]=k(""),[s,o]=k(!1),[i,l]=k(null),[d,m]=k(!1);G(()=>{t&&(m(!1),o(!1),l(null))},[t]),G(()=>{if(!e||!t){t||a("");return}const h=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
17
+ `).filter(x=>x.length>0);if(y.length<3){o(!1),m(!1),l(null),a("");return}const v=y.filter(x=>x.includes("CodeYam Log Level 1"));if(v.length>0){const x=v[v.length-1];a(x.replace(/.*CodeYam Log Level 1: /,""))}const b=y.find(x=>x.includes("$$INTERACTIVE_SERVER_URL$$:"));if(b){const x=b.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(x),m(!0)}y.some(x=>x.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=Z(()=>{a(""),o(!1),l(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function ut({projectSlug:e,onClose:t}){const[r,a]=k("Loading logs..."),[s,o]=k(!0),[i,l]=k(!0),[d,m]=k("all"),u=fe(null);return G(()=>{const h=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
18
+ `).filter(y=>{if(y.length===0)return!1;const v=y.match(/^.*CodeYam Log Level (\d+):/);return!!v&&Number(v[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
19
+ `))}i&&u.current&&setTimeout(()=>{u.current?.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),s){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),G(()=>{const h=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:h=>m(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function qs({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){const[d,m]=k(!1),[u,h]=k(!1),[p,f]=k(!1),[g,y]=k(null),v=!!i||o.length>0,b=!!i,x=i?.entities||r,N=!!e?.analysisCompletedAt;e?.readyToBeCaptured,e?.capturesCompleted;const w=e?.currentEntityShas&&e.currentEntityShas.length>0,E=v,{lastLine:C,isCompleted:S}=Ue(t,E),A=b||E&&!S&&!v,I=(()=>{if(E)return!1;const L=Date.now()-30*1e3;if(e?.createdAt&&w){const Y=e.analysisCompletedAt||e.createdAt;if(new Date(Y).getTime()>L)return!0}if(l.length>0){const Y=l[0],J=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt;if(J&&new Date(J).getTime()>L)return!0}return!1})(),R=(()=>{const L=Date.now()-1440*60*1e3;if(e?.createdAt&&w){const Y=e.analysisCompletedAt||e.createdAt;if(new Date(Y).getTime()>L)return!0}if(l.length>0){const Y=l[0],J=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt;if(J&&new Date(J).getTime()>L)return!0}return!1})(),M=a||A||s>0||I;G(()=>{const T=i?.id||null;M?T!==g&&(h(!0),f(!1),g!==null&&y(null)):(g!==null&&y(null),!R&&u&&!p&&h(!1))},[M,R,u,p,g,i?.id]);const P=()=>i?`Analyzing${o.length>0?` (+${o.length} queued)`:""}`:o.length>0?`${o.length} job${o.length>1?"s":""} queued`:A?N?"Capture in Progress":"Analysis in Progress":I?"Recently completed":"Idle",F=()=>A?"settings":s>0?"clock":I?"check":"activity";return c(te,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded-lg shadow-lg border-2 transition-all duration-200 border-gray-300 ${u?"min-w-[400px] max-w-[600px]":"w-auto"}`,style:M?{borderColor:"#005C75"}:{},children:[!u&&c("div",{onClick:()=>{h(!0),f(!0),y(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors rounded-lg",title:"Click to expand",children:[n("span",{className:`${A?"animate-spin":""}`,children:F()==="activity"?n(Nn,{style:{width:"20px",height:"20px",strokeWidth:1.5}}):F()==="check"?n(Ct,{size:20,style:{color:"#10B981",strokeWidth:1.5}}):F()==="settings"?n(ot,{size:20,style:{strokeWidth:1.5}}):n(Wt,{size:20,style:{strokeWidth:1.5}})}),c("span",{className:"text-sm font-medium text-gray-700",children:["Activity: ",P()]})]}),u&&c("div",{children:[c("div",{className:"flex justify-between items-center p-3 w-full",children:[c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>{h(!1),y(i?.id||null)},className:"p-1.5 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors shadow-sm flex items-center justify-center",title:"Collapse","aria-label":"Collapse notification",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("div",{className:`${A?"animate-spin":""}`,children:A?n(ot,{size:24,style:{strokeWidth:1.5}}):I?n(Ct,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Nn,{style:{width:"24px",height:"24px",strokeWidth:1.5}})}),n("div",{className:"flex-1 min-w-0",children:n("h3",{className:"text-sm font-bold text-gray-900 mb-1",children:A?N?"Capture in Progress":"Analysis in Progress":I?"Analysis Complete":"Activity"})})]}),n("div",{children:n("button",{onClick:()=>m(!0),className:"px-3 py-1.5 text-white rounded-md text-xs font-semibold transition-colors whitespace-nowrap",style:{backgroundColor:"#005C75"},onMouseEnter:T=>T.currentTarget.style.backgroundColor="#004560",onMouseLeave:T=>T.currentTarget.style.backgroundColor="#005C75",title:"View full analysis logs",children:"View Logs"})})]}),c("div",{className:"px-4 pb-4 border-t border-gray-200 pt-3",children:[!M&&!R&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs text-gray-600 mb-2",children:"No recent analysis activity. Start an analysis to see progress here."}),c("div",{className:"text-xs text-gray-500 space-y-1",children:[n("div",{children:'• Click "Analyze" on any entity in the Git or Files view'}),c("div",{children:["• Or run"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"codeyam analyze"})," ","from the command line"]})]})]}),A&&N&&(e?.readyToBeCaptured??0)>0&&c("div",{className:"mb-3 border rounded-md p-2",style:{backgroundColor:"#E8F4F8",borderColor:"#B3D9E8"},children:[n("p",{className:"text-xs font-semibold mb-1",style:{color:"#003D52"},children:"Capture Progress:"}),c("p",{className:"text-xs",style:{color:"#005C75"},children:[e?.capturesCompleted??0," of"," ",e?.readyToBeCaptured??0," entities captured"]})]}),A&&x.length>0&&c("div",{className:"mb-3",children:[c("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:[i?"Analyzing":N?"Capturing":"Analyzing"," ",x.length===1?"Entity":"Entities",":"]}),n("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:x.map(T=>c(ee,{to:`/entity/${T.sha}`,className:"flex items-center gap-1.5 text-xs font-medium truncate hover:underline",style:{color:"#005C75"},title:`${T.name} - ${T.filePath}`,children:[n(Oe,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[T.name,c("span",{className:"text-gray-500 ml-1",children:["(",T.filePath,")"]})]})]},T.sha))})]}),A&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs font-semibold text-gray-700 mb-1",children:"Current Step:"}),n("p",{className:"text-xs font-mono text-gray-600 break-words",children:C||"Starting analysis..."})]}),o.length>0&&i&&c("div",{className:"mb-3",children:[c("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:["Queued (",o.length,"):"]}),n("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.map(T=>c("div",{className:"space-y-1",children:[T.entities.length>0?T.entities.slice(0,2).map(L=>c(ee,{to:`/entity/${L.sha}`,className:"flex items-center gap-1.5 text-xs font-medium truncate hover:underline",style:{color:"#005C75"},title:`${L.name} - ${L.filePath}`,children:[n(Wt,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[L.name,c("span",{className:"text-gray-500 ml-1",children:["(",L.filePath,")"]})]})]},L.sha)):c("div",{className:"flex items-center gap-1.5 text-xs text-gray-600 truncate",children:[n(Wt,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),T.entities.length," ",T.entities.length===1?"entity":"entities"]}),T.entities.length>2&&c("div",{className:"text-xs text-gray-500 italic pl-4",children:["+",T.entities.length-2," more"]})]},T.id))})]}),R&&l.length>0&&c("div",{className:"mb-3",children:[n("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:"Recently Completed:"}),n("div",{className:"space-y-2",children:l.slice(0,3).map((T,L)=>{const Y=T.entities||[];Y.length||T.currentEntityShas?.length||T.entityCount;const J=T.analysisCompletedAt||T.archivedAt||T.createdAt||"",O=(()=>{if(!J)return"";const B=Date.now()-new Date(J).getTime(),H=Math.floor(B/6e4),j=Math.floor(B/36e5);return j>0?`${j}h ago`:H>0?`${H}m ago`:"just now"})();return n("div",{className:"text-xs bg-gray-50 rounded-md p-2",children:c("div",{className:"flex justify-between items-start mb-1",children:[n("div",{children:Y.length>0&&c("div",{className:"text-gray-600 text-[10px] space-y-0.5",children:[Y.slice(0,3).map(B=>c("div",{className:"flex items-center gap-1 truncate",children:[c(ee,{to:`/entity/${B.sha}`,className:"flex items-center gap-1 hover:underline truncate",style:{color:"#005C75"},children:[n(Oe,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),n("span",{className:"truncate",children:B.name})]}),c("span",{className:"text-gray-500 ml-1",children:["(",B.filePath,")"]})]},B.sha)),Y.length>3&&c("div",{className:"text-gray-500",children:["+",Y.length-3," more"]})]})}),n("div",{className:"text-gray-500 text-[10px]",children:O})]})},L)})})]}),n("div",{className:"mt-3 pt-3 border-t border-gray-200",children:n(ee,{to:"/activity",className:"text-xs font-medium hover:underline",style:{color:"#005C75"},children:"View All Activity →"})})]})]})]}),d&&t&&n(ut,{projectSlug:t,onClose:()=>m(!1)})]})}function Pe(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Et(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:m,updated_at:u,...h}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(Fe):void 0,g=d?Qe(d):void 0;return Pe({...h,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:m,updatedAt:u})}function Yn(e){return Pe({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 zn(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:m,...u}=e;return Pe({...u,branches:t?t.map(it):void 0,files:r?r.map(Yn):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function Ws(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Pe({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:l})}function Gs(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:l,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Pe({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:l,user:m})}function qr(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,m=s?Fe(s):void 0,u=o?o.map(Ws):void 0,h=i?i.map(Gs):void 0;return Pe({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:m,userScenarios:u,comments:h})}function Hs(e){return Pe({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Fe(e.analysis):void 0,entity:e.entity?Et(e.entity):void 0,branch:e.branch?it(e.branch):void 0,createdAt:e.created_at})}function Fe(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:m,entity:u,commit:h,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:v,branch_commit_sha:b,committed_at:x,completed_at:N,created_at:w,updated_at:E,indirect:C,...S}=e,A=u?Et(u):void 0,I=m?Yn(m):void 0,R=p?zn(p):void 0,M=h?Qe(h):void 0,P=f?f.map(qr):void 0,F=g?g.map(Hs):void 0,_=F?F.map(T=>T.branch):void 0;return Pe({...S,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:A,file:I,commit:M,project:R,scenarios:P,analysisBranches:F,branches:_,dependencyAnalyzedTreeSha:y,analyzedTreeSha:v,branchCommitSha:b,committedAt:x,completedAt:N,createdAt:w,updatedAt:E,indirect:!!C})}function Bn(e){return Pe({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Qe(e.commit):void 0,branch:e.branch?it(e.branch):void 0})}function Ks(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return Pe({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function Qe(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:m,analyses:u,entities:h,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,v=a?it(a):void 0,b=i?it(i):void 0,x=s?.length>0?Ks(s[s.length-1]):void 0,N=(u??[]).map(Fe),w=(h??[]).map(Et),E=p?.length>0?p.map(Bn):void 0;return m&&(m.username=m.preferredUsername??m.username),Pe({...y,projectId:t,branchId:r,branch:v,backgroundJob:x,mergedBranchId:o,mergedBranch:b,aiMessage:l,htmlUrl:d,author:m,analyses:N,entities:w,commitBranches:E,committedAt:f,analyzedAt:g})}function it(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:l,primary:d,...m}=e,u=a?a.map(Qe):void 0,h=s?s.flatMap(p=>Fe(p.analysis)):void 0;return Pe({...m,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}class Vs{#e=new Js;transformQuery(t){return this.#e.transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}class Js extends cs{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 z=()=>null,Qs={analyzed_at:z(),configuration:z(),content_changed_at:z(),created_at:z(),description:z(),github_token:z(),id:z(),metadata:z(),name:z(),path:z(),slug:z(),team_id:z(),updated_at:z()},Zs=Object.keys(Qs),Xs={active:z(),analysis_id:z(),branch_id:z(),created_at:z(),entity_sha:z(),id:z()},eo=Object.keys(Xs),to={active_at:z(),content_changed_at:z(),created_at:z(),id:z(),metadata:z(),name:z(),primary:z(),project_id:z(),ref:z(),sha:z(),updated_at:z()},Wr=Object.keys(to),no={ai_message:z(),analyzed_at:z(),author_github_username:z(),branch_id:z(),committed_at:z(),created_at:z(),files:z(),html_url:z(),id:z(),merged_branch_id:z(),message:z(),metadata:z(),project_id:z(),sha:z(),title:z(),url:z()},ro=Object.keys(no),ao={commit_id:z(),created_at:z(),description:z(),documentation:z(),entity_type:z(),file_id:z(),file_path:z(),metadata:z(),name:z(),project_id:z(),quality:z(),sha:z(),updated_at:z()},Gr=Object.keys(ao),so={active:z(),branch_id:z(),entity_sha:z()},oo=Object.keys(so),io={created_at:z(),deleted:z(),id:z(),metadata:z(),name:z(),path:z(),project_id:z(),updated_at:z()},lo=Object.keys(io),co={analysis_id:z(),approved:z(),created_at:z(),description:z(),id:z(),metadata:z(),name:z(),previous_version_id:z(),project_id:z()},Un=Object.keys(co),uo=!!Je("ENABLE_QUERY_LOGGING"),mo=!!Je("ENABLE_QUERY_ERROR_LOGGING");Je("USE_LOCAL_POSTGRESQL_FOR_TESTING");let Lt;function ce(){if(!Lt){const e=Kr();if(e==="sqlite")Lt=ho();else if(e==="postgresql")Lt=po();else throw new Error(`Unknown database type: ${e}`)}return Lt}function ho(e){if(e||(e=Je("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=W.existsSync(e),r=K.dirname(e);if(!W.existsSync(r))W.mkdirSync(r,{recursive:!0,mode:493});else try{W.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new os(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const s=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&s.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(s){console.error("CodeYam DB ERROR: Failed to verify database schema:",s)}return new Yr({dialect:new us({database:a}),plugins:[new ds,new Vs],log:Hr})}function po(){const e=go();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new is({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Yr({dialect:new ms({pool:t}),log:Hr})}let pn=null;function Ze(){return pn||(pn=fo(Kr())),pn}function Hr(e){e.level==="error"?mo&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):uo&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function fo(e){if(e==="sqlite")return hs;if(e==="postgresql")return ps;throw new Error(`Unknown database type: ${e}`)}function Kr(){if(Je("SQLITE_PATH"))return"sqlite";if(Je("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function go(){const e=Je("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Je(e){return typeof window<"u"?window.env?.[e]:process.env[e]}var _t=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(_t||{});const on="Default Scenario";let yo="<main>";function xo(){return yo}function oe(...e){const t=xo(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
20
+ ${s.stack}`:typeof s=="object"?bo(s):String(s)}).filter(Boolean).join(`
21
+ `),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
22
+ `);return}console.log(a.replace(/\n/g,"\r"))}function bo(e,t=2){function r(a,s=new WeakMap){return a===null||typeof a!="object"?a:s.has(a)?`"[Circular: ${a.constructor.name}]"`:(s.set(a,!0),Array.isArray(a)?`[${a.map(l=>{const d=r(l,s);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,s):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const s=r(e);if(!t)return s;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:a,serialized:s}),s}}}function Jt(e,t){try{let r=function(o){if(pe.isFunctionDeclaration(o)&&bt(o)){const i=o.name?.text||"default",l=o.getText(a),d=fn(o);s.push({name:i,code:l,sha:tt(t,i,l),entityType:"function",isDefault:d})}else if(pe.isClassDeclaration(o)&&bt(o)){const i=o.name?.text||"default",l=o.getText(a),d=fn(o),m=l.includes("React.")||l.includes("jsx")||l.includes("tsx");s.push({name:i,code:l,sha:tt(t,i,l),entityType:m?"component":"class",isDefault:d})}else if(pe.isInterfaceDeclaration(o)&&bt(o)){const i=o.name.text,l=o.getText(a);s.push({name:i,code:l,sha:tt(t,i,l),entityType:"interface",isDefault:!1})}else if(pe.isTypeAliasDeclaration(o)&&bt(o)){const i=o.name.text,l=o.getText(a);s.push({name:i,code:l,sha:tt(t,i,l),entityType:"type",isDefault:!1})}else if(pe.isVariableStatement(o)&&bt(o)){const i=fn(o);o.declarationList.declarations.forEach(l=>{if(pe.isIdentifier(l.name)){const d=l.name.text,m=o.getText(a),u=l.initializer?.getText(a)||"",h=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&u.includes("=>")&&(u.includes("<")||u.includes("React."));s.push({name:d,code:m,sha:tt(t,d,m),entityType:h?"component":"variable",isDefault:i})}})}else if(pe.isExportAssignment(o)){const i=o.getText(a);s.push({name:"default",code:i,sha:tt(t,"default",i),entityType:"unknown",isDefault:!0})}pe.forEachChild(o,r)};const a=pe.createSourceFile(t,e,pe.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function bt(e){if(!pe.canHaveModifiers(e))return!1;const t=pe.getModifiers(e);return t?t.some(r=>r.kind===pe.SyntaxKind.ExportKeyword):!1}function fn(e){if(!pe.canHaveModifiers(e))return!1;const t=pe.getModifiers(e);return t?t.some(r=>r.kind===pe.SyntaxKind.DefaultKeyword):!1}function tt(e,t,r){const a=Rn.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function ln(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}function vo(e){const{jsonObjectFrom:t}=Ze();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 wo({ids:e,analysisId:t}){const r=ce();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw oe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw oe("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function Co(...e){try{const t=Rn.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 sr(e,t){return t.map(r=>No(e,r))}function No(e,t){return ke` ${ke.ref(e)}.${ke.ref(t)}`.as(t)}function So(e,t,r){return t.map(a=>Ao(e,a,r))}function Ao(e,t,r){return ke` ${ke.ref(e)}.${ke.ref(t)}`.as(`_cy_${r}:${t}`)}function Eo(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const _o=50;function Po(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,a)=>e.slice(a*t,a*t+t))}function or({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:l}){const d=ce(),{jsonObjectFrom:m,jsonArrayFrom:u}=Ze();let h=d.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(o){if(o.length===0)return null;h=h.where("commit_id","in",o)}return a&&(h=h.where("entity_name","=",a)),s&&(h=h.where("entity_sha","in",s)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),d.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[m(p.selectFrom("entities").select(sr("entities",Gr)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),u(p.selectFrom("scenarios").select(sr("scenarios",Un)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),u(p.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Nt(e){const{ids:t,fileIds:r,entityShas:a,commitIds:s}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:s,key:"commitIds"}}).find(([d,{arr:m}])=>m?.length>0);let l=[];if(i){const[d,{arr:m,key:u}]=i,h=Po(m,_o),p=[];for(let f=0;f<h.length;f++){const g=h[f],v=await or({...e,[u]:g}).execute();v&&p.push(...v)}l=p}else{const m=await or(e).execute();if(!m||m.length===0)return oe("CodeYam: No analyses found",null,e),null;l=m}return l.length===0?null:l.map(Fe)}catch(o){return oe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Mo(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=Ze();let s=e.selectFrom("analysis_branches").select(eo).select(o=>a(o.selectFrom("branches").select(Wr).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function qe({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}){const f=ce();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):a&&(g=g.where("file_id","=",a)),o&&(g=g.where("entity_name","=",o)),s?g=g.where("commit_id","=",s):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:y,jsonArrayFrom:v}=Ze();g=g.select(x=>{const N=[];return N.push(y(x.selectFrom("entities").select(Gr).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&N.push(y(x.selectFrom("files").select(lo).whereRef("files.id","=","analyses.file_id")).as("file")),m&&N.push(y(x.selectFrom("projects").select(Zs).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&N.push(v(x.selectFrom("scenarios").select(Un).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&N.push(Mo(x,w=>w.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&N.push(y(x.selectFrom("commits").select(ro).select(w=>vo(w).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),N});const b=await g.executeTakeFirst();return b?Fe(b):(oe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null)}catch(g){return oe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null}}async function Vr({projectId:e,ids:t,names:r,includeInactive:a}){const s=ce();try{let o=s.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return a||(o=o.where("active_at","is not",null)),(await o.execute()).map(it)}catch(o){return oe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function ko({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ce();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,m=>m.select(So("branches",Wr,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const l=await i.execute();return!l||l.length===0?null:l.map(m=>Eo(m,"branch")).map(Bn)}catch(i){return oe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function To(e){if(e.length===0)return new Map;const t=ce();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(o=>{o.branch_id&&a.add(o.branch_id),o.merged_branch_id&&a.add(o.merged_branch_id)}),a.size===0)return new Map;const s=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(s.map(o=>[o.id,o]))}catch(r){return oe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Io(e){if(e.length===0)return new Map;const t=ce(),{jsonObjectFrom:r,jsonArrayFrom:a}=Ze();try{const s=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(Un).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(s){return oe("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function Ro(e){if(e.length===0)return new Map;const t=ce();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(s=>{const o=a.get(s.commit_id)||[];o.push(s),a.set(s.commit_id,o)}),a}catch(r){return oe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Qt({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10}){if(!e&&!r)throw new Error("Must provide projectId or ids");const i=ce(),{jsonObjectFrom:l}=Ze();try{let d=i.selectFrom("commits").selectAll("commits").select(y=>[l(y.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",y.ref("commits.author_github_username"))).as("author")]);if(e&&(d=d.where("project_id","=",e)),r){if(r.length===0)return[];d=d.where("id","in",r)}if(a){if(a.length===0)return[];d=d.where("sha","in",a)}if(s&&s.length>0){const y=ke.join(s.map(v=>ke`${v}`),ke`, `);d=d.where(ke`
23
+ EXISTS (
24
+ SELECT 1
25
+ FROM json_each(${ke.ref("commits.files")}) AS f
26
+ WHERE json_extract(f.value, '$.fileName') IN (${y})
27
+ )
28
+ `)}t&&(d=d.where("branch_id","=",t));const m=await d.orderBy("committed_at","desc").limit(o).execute();if(!m||m.length===0)return[];const u=m.map(y=>y.id),[h,p,f]=await Promise.all([To(u),Io(u),Ro(u)]);return m.map(y=>{const v=y.branch_id?h.get(y.branch_id):void 0,b=y.merged_branch_id?h.get(y.merged_branch_id):void 0,x=p.get(y.id)||[],N=f.get(y.id)||[];return{...y,branch:v,mergedBranch:b,analyses:x,entities:N}}).map(Qe)}catch(d){return oe("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function lt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const l=[];for(let d=0;d<o.length;d+=50){const m=o.slice(d,d+50),u=await lt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:m});u&&l.push(...u)}return l}const i=ce();try{const d=await i.selectFrom("entities").selectAll("entities").$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!s,m=>m.where("entities.name","in",s)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!d||d.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):d.map(Et)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function jo(e,t){const{jsonArrayFrom:r}=Ze();let a=e.selectFrom("entity_branches").select(oo);return t&&(a=t(a)),r(a)}async function Jr({projectId:e,sha:t}){const r=ce();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>jo(s,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?Et(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&oe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return oe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const gn=1e3;async function Qr({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const m=t.slice(d,d+50),u=await Qr({projectId:e,filePaths:m,fileIds:r,fileNames:a});u&&l.push(...u)}return l}const s=ce(),o=[];let i=0;try{for(;;){let l=s.selectFrom("files").selectAll().where("project_id","=",e).limit(gn).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(a){if(a.length===0)return[];l=l.where("name","in",a)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<gn))break;i+=gn}return o?.map(Yn)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function $o({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ce().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=zn(l);return a&&(d.files=await Qr({projectId:d.id})),r&&(d.branches=await Vr({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Zt(e,t){const r={...e};for(const a in t){const s=t[a],o=e[a];s!=null&&typeof s=="object"&&!Array.isArray(s)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[a]=Zt(o,s):s!==void 0&&(r[a]=s)}return r}async function at({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ce().transaction().execute(async i=>{const l=await i.selectFrom("commits").selectAll().$if(!!e,u=>u.where("id","=",e)).$if(!!t,u=>u.where("sha","=",t)).executeTakeFirst();if(!l)return oe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)a.lastUpdatedAt??=new Date().toISOString(),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",d.currentRun?.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=Zt(r??{},{currentRun:a});else if(!r&&!o)return d;const m=r?Zt(d,r):d;if(s&&m.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",m.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${m.currentRun.analyzerPid}, capture=${m.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${m.currentRun.analysesCompleted}, captures=${m.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${m.historicalRuns?.length||0}`);const u={...m.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(u,null,2)),m.historicalRuns=[...m.historicalRuns||[],u],console.log(`[updateCommitMetadata] Historical runs after archiving: ${m.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(m.historicalRuns.map(h=>({entityShas:h.currentEntityShas,archivedAt:h.archivedAt,completed:{analyses:h.analysesCompleted,captures:h.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(m,Qe(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",l.id).returningAll().executeTakeFirst()?m:(oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(u){return oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,u),d}})}catch(i){return oe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function Zr(e,t,r="analysis"){try{return await ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return oe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Fe(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(oe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return oe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Pt(e,t,r="capture"){try{return await ce().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return oe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Fe(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(oe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return oe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Do({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ce().transaction().execute(async s=>{const o=await s.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return oe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const l=r?Zt(i,r):i;a&&await a(l,zn(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return oe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}function Lo(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,...l}=e;return delete l.userScenarios,delete l.comments,"created_at"in l&&delete l.created_at,{...l,id:t??At(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function Oo(e){if(e.length===0)return[];const t=ce(),r=e.map(Lo);try{return(await t.insertInto("scenarios").values(r).onConflict(ln(r[0],"id",["created_at"])).returningAll().execute()).map(qr)}catch(a){return oe("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function Fo(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??At(),commit_id:r,branch_id:a}}async function ir(e){if(e.length===0)return[];const t=ce(),r=e.map(Fo);try{return(await t.insertInto("commit_branches").values(r).onConflict(ln(r[0],"id",["created_at"])).returningAll().execute()).map(Bn)}catch(a){return oe("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function Yo(e,t){const r=ce(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(ln(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return oe("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}function zo(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:m,author:u,metadata:h,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??At(),project_id:a??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u?.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:m}}async function Bo({projectId:e,commits:t}){const r=ce();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d?.username&&d?.avatarUrl&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await Yo(i,a[i]);const s=t.map(i=>zo(i,e));return(await r.insertInto("commits").values(s).onConflict(ln(s[0],"id",["created_at"])).returningAll().execute()).map(Qe)}catch(a){return oe("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const Xt=K.join(ys.homedir(),".codeyam","secrets.json"),en=K.join(process.cwd(),".codeyam","secrets.json");async function mt(){let e={};try{if(W.existsSync(en)){const o=await ve.readFile(en,"utf8");e=JSON.parse(o)}}catch{console.warn(Vt.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(W.existsSync(Xt)){const o=await ve.readFile(Xt,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(Vt.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(t.ANTHROPIC_API_KEY=a);const s=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return s&&(t.GROQ_API_KEY=s),t}async function Uo(e,t=!0){const r=t?Xt:en,a=K.dirname(r);await ve.mkdir(a,{recursive:!0}),await ve.writeFile(r,JSON.stringify(e,null,2)),await ve.chmod(r,384)}function qo(e=!0){return e?Xt:en}async function lr(){const e=await mt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Wo(e){console.log(),console.log(Vt.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await xs({type:"password",name:"key",message:"OpenAI API Key",validate:s=>s&&!s.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function Go(e=!0){const t=await lr();if(t.isValid)return t.secrets;const r=await Wo(t.missing),s={...await mt(),...r};await Uo(s,e);const o=qo(e);return console.log(Vt.green(`✓ Configuration saved to ${o}`)),(await lr()).secrets}function Xr(e=process.cwd()){let t=K.resolve(e);const r=K.parse(t).root;for(;t!==r;){const s=K.join(t,".codeyam","config.json");if(W.existsSync(s))return t;t=K.dirname(t)}const a=K.join(r,".codeyam","config.json");return W.existsSync(a)?r:null}let ea=Xr();function ie(){return ea}function Ho(e){ea=e}function ta(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const Ko={"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>`};ta(Ko);const Vo={"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>`};ta(Vo);function En(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)}const a={...e};for(const s in t)if(t[s]===null)delete a[s];else if(Array.isArray(t[s])){a[s]=[];for(let o=0;o<t[s].length;o++){const i=t[s][o];typeof i=="object"&&i!==null?a[s][o]=En(a?.[s]?.[o],i,r):a[s][o]=i}}else typeof t[s]=="object"&&t[s]!==null?a[s]=En(a[s]??{},t[s],r):a[s]=t[s];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function Jo({projectId:e,commit:t,branch:r}){let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await ko({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=o.sort((d,m)=>(d.branch.metadata?.permanent?.order??999)-(m.branch.metadata?.permanent?.order??999))[0]?.branch,a&&r.metadata?.permanent?.order!==void 0&&(r.metadata?.permanent?.order<=a.metadata?.permanent?.order?a=r:s.active=!1);const l=o.filter(d=>d.active&&d.branch.id!==a.id||!d.active&&d.branch.id===a.id);l.length>0&&await ir(l.map(d=>({...d,active:d.branchId===a.id})))}o?.find(l=>l.branchId===s.branchId)||await ir([s])}function ht(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=ie();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return le.join(e,".codeyam","db.sqlite3")}async function Ae(){const e=await Go();process.env.SQLITE_PATH=ht(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Te(e){await Ae();const t=await $o({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const a=(await Vr({projectId:t.id,names:["_local"]}))?.[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:a}}async function Qo(e,t,r){await Ae();const a=Co(`${e.slug}-local-${Date.now()}-${Math.random()}`),s={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:r.map(i=>({fileName:i,status:"modified",patch:""})),metadata:{baseline:!1,receivedAt:new Date().toISOString()}},o=await Bo({projectId:e.id,commits:[s]});if(!o||o.length===0)throw new Error("Failed to create fake commit");return await Jo({projectId:e.id,commit:o[0],branch:t}),o[0]}async function Mt(){await Ae();const e=await lt({});if(!e||e.length===0)return e;const t=e.filter(l=>!l.metadata?.isSuperseded),r=t.map(l=>l.sha),a=t.map(l=>l.metadata?.previousVersionWithAnalyses).filter(l=>!!l),s=[...new Set([...r,...a])],o=await Nt({entityShas:s}),i=new Map;if(o)for(const l of o)i.has(l.entitySha)||i.set(l.entitySha,[]),i.get(l.entitySha).push(l);return t.map(l=>{const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const m=l.metadata?.previousVersionWithAnalyses;if(m){const u=i.get(m)||[];return{...l,analyses:u}}return{...l,analyses:[]}})}async function cn(e,t){await Ae();const r=await Nt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await Jr({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function Le(e){await Ae();const t=await Me();if(!t)return null;const{project:r}=await Te(t);return await Jr({projectId:r.id,sha:e})}async function na(e){await Ae();const t=[],r=[];if(e.metadata?.importedExports&&e.metadata.importedExports.length>0){const a=e.metadata.importedExports;for(const s of a){if(!s.filePath||!s.name)continue;const o=await lt({projectId:e.projectId,filePaths:[s.filePath],names:[s.name]});if(o&&o.length>0){const i=o[0],l=await Nt({entityShas:[i.sha],limit:1});let d,m,u;if(l&&l.length>0&&l[0].scenarios){const h=l[0],p=h.scenarios||[],f=p.length,g=p.find(v=>v.metadata?.screenshotPaths?.[0]);g&&(d=g.metadata?.screenshotPaths?.[0],m=g.name),u={status:i.metadata?.previousVersionWithAnalyses||h.entitySha!==i.sha?"out_of_date":"up_to_date",scenarioCount:f,timestamp:h.createdAt?new Date(h.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else u={status:"not_analyzed"};t.push({...i,screenshotPath:d,scenarioName:m,analysisStatus:u})}}}if(e.metadata?.importedBy){const a=[];for(const s in e.metadata.importedBy)for(const o in e.metadata.importedBy[s]){const i=e.metadata.importedBy[s][o];i.shas&&a.push(...i.shas)}if(a.length>0){const s=await lt({projectId:e.projectId,shas:a});if(s)for(const o of s){const i=await Nt({entityShas:[o.sha],limit:1});let l,d,m;if(i&&i.length>0&&i[0].scenarios){const u=i[0],h=u.scenarios||[],p=h.length,f=h.find(y=>y.metadata?.screenshotPaths?.[0]);f&&(l=f.metadata?.screenshotPaths?.[0],d=f.name),m={status:o.metadata?.previousVersionWithAnalyses||u.entitySha!==o.sha?"out_of_date":"up_to_date",scenarioCount:p,timestamp:u.createdAt?new Date(u.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else m={status:"not_analyzed"};r.push({...o,screenshotPath:l,scenarioName:d,analysisStatus:m})}}}return{importedEntities:t,importingEntities:r}}async function Me(){try{const e=ie();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await ge.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Xe(){await Ae();try{const e=await Me();if(!e)return null;const{project:t,branch:r}=await Te(e),a=await Qt({projectId:t.id,branchId:r.id,limit:1});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function ra(){try{const e=ie();if(!e)return null;const t=le.join(e,".codeyam","config.json");return JSON.parse(await ge.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function aa(e){try{const t=ie();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=le.join(t,e.filePath);return await ge.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function sa(e){if(await Ae(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await lt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await Nt({entityShas:r}),s=new Map;if(a)for(const i of a)s.has(i.entitySha)||s.set(i.entitySha,[]),s.get(i.entitySha).push(i);for(const[i,l]of s.entries())l.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,l)=>{const d=i.analyses[0]?.createdAt||i.createdAt||"",m=l.analyses[0]?.createdAt||l.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),o}async function oa(e){try{const t=ie();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=le.join(t,".codeyam","config.json"),a=await ge.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await ge.writeFile(r,i,"utf8"),s.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await Do({projectSlug:s.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Zo=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Mt,getAnalysesForEntity:cn,getCurrentCommit:Xe,getEntityBySha:Le,getEntityCodeFromFilesystem:aa,getEntityHistory:sa,getProjectConfig:ra,getProjectSlug:Me,getRelatedEntities:na,updateProjectConfig:oa},Symbol.toStringTag,{value:"Module"})),ia="secrets.json";function la(e){return le.join(e,".codeyam",ia)}function ca(){return le.join(An.homedir(),".codeyam",ia)}async function dn(e){let t={};try{const r=ca(),a=await ge.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=la(e),a=await ge.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function Xo(e,t,r=!0){const a=r?ca():la(e),s=le.dirname(a);await ge.mkdir(s,{recursive:!0}),await ge.writeFile(a,JSON.stringify(t,null,2)+`
29
+ `,"utf-8")}async function ei(e){const t=await dn(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 ti="/assets/globals-BGS74ED-.css";function ni({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=k(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(ee,{to:a,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors","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"})})})]})})}const ri=()=>[{rel:"stylesheet",href:ti},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function ai({request:e,context:t}){try{const r=ie()||process.cwd(),[a,s,o]=await Promise.all([Xe(),Me(),dn(r)]);if(!s)throw new Error("Project slug not found");const l=t.analysisQueue?.getState(),d=await Promise.all((l?.jobs||[]).map(async w=>{const E=[];if(w.entityShas&&w.entityShas.length>0){const C=w.entityShas.map(A=>Le(A)),S=await Promise.all(C);E.push(...S.filter(A=>A!==null))}return{...w,entities:E}}));let m=null;if(l?.currentlyExecuting){const w=l.currentlyExecuting,E=[];if(w.entityShas&&w.entityShas.length>0){const C=w.entityShas.map(A=>Le(A)),S=await Promise.all(C);E.push(...S.filter(A=>A!==null))}m={...w,entities:E}}let u=a?.metadata?.currentRun?.currentEntityShas||[];if(u.length===0){const w=a?.metadata?.historicalRuns||[];if(w.length>0){const C=[...w].sort((S,A)=>{const I=S.archivedAt||S.createdAt||"";return(A.archivedAt||A.createdAt||"").localeCompare(I)})[0];if(C){const S=C.analysisCompletedAt||C.createdAt;if(S){const A=new Date(S).getTime(),R=Date.now()-1440*60*1e3;A>R&&(u=C.currentEntityShas||[])}}}}const p=(await Promise.all(u.map(w=>Le(w)))).filter(w=>w!==null),f=[];o.ANTHROPIC_API_KEY&&f.push("ANTHROPIC_API_KEY"),o.GROQ_API_KEY&&f.push("GROQ_API_KEY"),o.OPENAI_API_KEY&&f.push("OPENAI_API_KEY"),o.OPENROUTER_API_KEY&&f.push("OPENROUTER_API_KEY");const{project:g,branch:y}=await Te(s),v=await Qt({projectId:g.id,branchId:y.id,limit:20}),b=[];for(const w of v){const E=w.metadata?.historicalRuns||[];for(const C of E){const S=C.currentEntityShas||[];if(S.length>0){const A=S.map(M=>Le(M)),R=(await Promise.all(A)).filter(M=>M!==null);b.push({...C,entities:R})}else b.push(C)}}const x=b.sort((w,E)=>{const C=w.archivedAt||w.analysisCompletedAt||w.createdAt||"";return(E.archivedAt||E.analysisCompletedAt||E.createdAt||"").localeCompare(C)}),N={currentRun:a?.metadata?.currentRun,projectSlug:s,currentEntities:p,availableAPIKeys:f,queuedJobCount:d.length,queueJobs:d,currentlyExecuting:m,historicalRuns:x};return D(N)}catch(r){return console.error("Failed to load root data:",r),D({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[]})}}function si(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l}=De(),{toasts:d,closeToast:m}=Fn(),u=dt(),h=fe(u),p=Ir();G(()=>{h.current=u},[u]);const f=p.pathname.startsWith("/entity/")&&p.pathname.includes("/edit/")||p.pathname.startsWith("/dev/");return G(()=>{const g=new EventSource("/api/events");let y=null,v=0;const b=2e3;return g.addEventListener("message",x=>{if(JSON.parse(x.data).type==="db-change"){const w=Date.now(),E=w-v;E<b?(y&&clearTimeout(y),y=setTimeout(()=>{h.current.revalidate(),v=Date.now(),y=null},b-E)):(h.current.revalidate(),v=w)}}),g.addEventListener("error",x=>{console.error("SSE connection error:",x)}),()=>{y&&clearTimeout(y),g.close()}},[]),c(te,{children:[c("div",{className:`min-h-screen ${f?"":"grid"} bg-cygray-10`,style:f?void 0:{gridTemplateColumns:"96px minmax(900px, 1fr)"},children:[!f&&n(Ys,{}),c("div",{className:"max-h-screen overflow-auto bg-white",children:[a.length===0&&n(ni,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),n(Fa,{})]})]}),n(Us,{toasts:d,onClose:m}),n(qs,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const oi=Ie(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n($a,{}),n(Da,{})]}),c("body",{children:[n(zs,{children:n(si,{})}),n(La,{}),n(Oa,{})]})]})}),ii=Object.freeze(Object.defineProperty({__proto__:null,default:oi,links:ri,loader:ai},Symbol.toStringTag,{value:"Module"})),da=jr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),qn=()=>{const e=$r(da);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},un=({children:e})=>{const[t,r]=k({height:720,width:1200}),[a,s]=k(1),[o,i]=k(1200),l=fe(null),d=Z(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),m=Z(h=>{s(h)},[]),u=Z(h=>{i(h)},[]);return n(da.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},li=bs,ci=typeof window<"u",di=1200,ui=720,cr=30,mi=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const[m,u]=k(!1),[h,p]=k(!1),[f,g]=k(di),[y,v]=k(ui),[b,x]=k(null),[N,w]=k(null),{dimensions:E,updateDimensions:C,iframeRef:S,updateScale:A,updateMaxWidth:I}=qn(),R=ne(()=>Math.min(1,f/E.width),[f,E.width]),M=N!==null?N:R;G(()=>{m||(A(M),l?.(M))},[M,A,l,m]),G(()=>{I(f)},[f,I]);const P=Z(()=>{u(!0),w(R)},[R]),F=Z(()=>{u(!1),w(null)},[]),_=Z((O,B)=>{const H=N!==null?N:1,j=Math.round(B.size.width/H);C({width:j}),d?.(j,E.height)},[C,N,d,E.height]),T=Z(()=>{setTimeout(()=>{p(!0)},100),i&&i()},[i]);G(()=>{const O=B=>{if(B.data.type==="codeyam-resize"){if(t&&B.data.name!==t||E.height===B.data.height||B.data.height===0)return;C({height:B.data.height})}};return window.addEventListener("message",O),()=>{window.removeEventListener("message",O)}},[S,t,a,E,C]),G(()=>{h&&o&&o(S.current)},[h,o,S]),G(()=>{if(!t)return;const O=setInterval(()=>{S?.current?.contentWindow?.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(O)},[t,S]),G(()=>{const O=()=>{const B=document.getElementById("scenario-container");if(!B)return;const H=B.getBoundingClientRect(),j=B.clientWidth-cr*2,U=window.innerHeight-H.top-cr*2,$=Math.max(U,400),q=window.innerHeight-H.top;g(j),v($),x(q)};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]),G(()=>{C({width:a,height:s})},[a,s,C]);const L=ne(()=>E.width*M,[E.width,M]),Y=ne(()=>{const O=E.height,B=O*M;return O&&O!==720&&O!==900&&B<y?B:y},[E.height,y,M]),J=Z(()=>{window.history.back()},[]);return ci?c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[m&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
30
+ .react-resizable-handle-e {
31
+ display: flex !important;
32
+ align-items: center !important;
33
+ justify-content: center !important;
34
+ width: 6px !important;
35
+ height: 48px !important;
36
+ right: -8px !important;
37
+ top: 50% !important;
38
+ transform: translateY(-50%) !important;
39
+ cursor: ew-resize !important;
40
+ background: #d1d5db !important;
41
+ border-radius: 3px !important;
42
+ opacity: 0 !important;
43
+ transition: all 0.2s ease !important;
44
+ }
45
+ .react-resizable-handle-e:hover {
46
+ opacity: 0.8 !important;
47
+ background: #9ca3af !important;
48
+ }
49
+ .react-resizable:hover .react-resizable-handle-e {
50
+ opacity: 0.4 !important;
51
+ }
52
+ `}),n(li,{width:L,height:Y,minConstraints:[300,200],maxConstraints:[f,y],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:P,onResizeStop:F,onResize:_,children:n("div",{className:"overflow-auto",style:{width:`${L}px`,height:`${Y}px`},children:n("div",{style:{width:`${E.width}px`,height:`${E.height}px`,transform:`scale(${M})`,transformOrigin:"top left"},children:r?n("iframe",{ref:S,className:"w-full h-full rounded-lg",src:r,onLoad:T,sandbox:"allow-scripts allow-same-origin"}):c("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:J,children:"Go back"})]})})})},`resizable-box-${e}`)]}):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..."})})};function hi({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[m,u]=k(!1),[h,p]=k(String(r)),[f,g]=k(String(a)),[y,v]=k(!1),[b,x]=k(!1),N=fe(null);G(()=>{y||p(String(r))},[r,y]),G(()=>{b||g(String(a))},[a,b]),G(()=>{const P=F=>{N.current&&!N.current.contains(F.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const w=ne(()=>{const P=e.find(_=>_.width===r&&_.height===a);if(P)return P.name;const F=t.find(_=>_.width===r&&_.height===a);return F?F.name:"Custom"},[e,t,r,a]),E=w==="Custom",C=P=>{o(P.width,P.height),u(!1)},S=P=>{const F=P.target.value;p(F);const _=parseInt(F,10);!isNaN(_)&&_>0&&o(_,a)},A=P=>{const F=P.target.value;g(F);const _=parseInt(F,10);!isNaN(_)&&_>0&&o(r,_)},I=()=>{v(!1);const P=parseInt(h,10);(isNaN(P)||P<=0)&&p(String(r))},R=()=>{x(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&g(String(a))},M=P=>{(P.key==="Enter"||P.key==="Escape")&&P.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:N,children:[c("button",{onClick:()=>u(!m),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(te,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(P=>c("button",{onClick:()=>C(P),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:P.name}),c("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]},P.name))]}),t.length>0&&c(te,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((P,F)=>P.width-F.width).map(P=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>C(P),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:P.name}),c("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]}),l&&n("button",{onClick:F=>{F.stopPropagation(),w===P.name&&e.length>0&&o(e[0].width,e[0].height),l(P.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},P.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:S,onFocus:()=>v(!0),onBlur:I,onKeyDown:M,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:A,onFocus:()=>x(!0),onBlur:R,onKeyDown:M,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),s!==void 0&&s<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*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 yn(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const a of e)if(a.name===t||a.title===t||a.id===t)return a}return e[t]}function _n(e){return e&&(typeof e=="object"||Array.isArray(e))}function pi(e){return Array.isArray(e)?e.length:void 0}function fi(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,s)=>s.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((s,o)=>{const i=_n(t[s]),l=_n(t[o]);return i&&!l?1:!i&&l?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function gi({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),c("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function yi({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=Z(()=>{s&&s(e)},[s,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var ua=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(ua||{});const xi=({name:e,value:t,options:r,onChange:a})=>{const s=Z(o=>{a({target:{name:e,value:o.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:s,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},bi=({name:e,value:t,onChange:r})=>{const a=Z(s=>{const o=s.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
53
+ bg-gray-300 checked:bg-blue-600
54
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
55
+ after:bg-white after:rounded-full after:transition-transform
56
+ checked:after:translate-x-4`})})};function vi({dataType:e,path:t,value:r,onChange:a}){const s=ne(()=>t[t.length-1],[t]),o=ne(()=>t.join("-"),[t]),i=Z(d=>{a(t,d.target.value)},[a,t]),l=Z(d=>{a(t,d.target.value)},[a,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(xi,{name:o,value:r,options:e.split("|"),onChange:i}):e===ua.BOOLEAN?n(bi,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function wi({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=k(!1),[l,d]=k(""),m=Z(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(v=>v.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(v=>v.name===on),f=await s(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(v,b)=>{const x=Object.assign({},v);return y(v)&&y(b)&&Object.keys(b).forEach(N=>{y(b[N])?N in v?x[N]=g(v[N],b[N]):Object.assign(x,{[N]:b[N]}):Object.assign(x,{[N]:b[N]})}),x},y=v=>v&&typeof v=="object"&&!Array.isArray(v);h.metadata.data=g(g(p?.metadata.data||{},h.metadata.data),f.data||{}),a(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,a,s]),u=Z(h=>{d(h.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>{m()},children:o?c(te,{children:[c("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Ci({namedPath:e,path:t,last:r,onClick:a}){const s=Z(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:s,children:e[e.length-1]})}function Ni({dataItem:e,onClick:t}){const r=Z(()=>t([]),[t]),a=ne(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>c("div",{className:"flex items-center gap-1",children:[n(Ci,{namedPath:e.namedPath.slice(0,o+a+1),path:e.path.slice(0,o+a+1),last:o+a===e.namedPath.length-1,onClick:t}),o+a<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${s}-${o+a}`))]})}function dr({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=ne(()=>r.data,[r]),m=ne(()=>fi(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Ni,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(wi,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m?.map((u,h)=>{if(_n(d[u])){let f=u;isNaN(Number(u))||(f=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],y=[...r.namedPath,f];return n(yi,{path:g,namedPath:y,isArray:Array.isArray(d),count:pi(d[u]),onClick:a},`data-${u}-${h}`)}if(u==="id")return null;const p=[...r.path,u];return n(vi,{dataType:r.structure?.[u]??"string",path:p,value:d[u],onChange:s},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l?.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?.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled: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?.message&&!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 ur({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=k(r),l=[];return a&&l.push("border-t"),s&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const Si=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:m})=>{const u=Z((S,A)=>{const I=Object.assign({},S),R=M=>M&&typeof M=="object"&&!Array.isArray(M);return R(S)&&R(A)&&Object.keys(A).forEach(M=>{R(A[M])?M in S?I[M]=u(S[M],A[M]):Object.assign(I,{[M]:A[M]}):Object.assign(I,{[M]:A[M]})}),I},[]),[h,p]=k({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=k(null),y=ne(()=>({...h.data}),[h]),v=ne(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),b=ne(()=>{const S={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(S).reduce((A,I)=>{if(I.includes(".")){const[R,M]=I.split(".");A[R]||(A[R]={}),A[R][M]=S[I]}else A[I]=S[I];return A},{})},[r]),x=Z(async S=>{S.preventDefault();const I=S.target.querySelector('input[name="recapture"]')?.value==="true",R={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:I,dataToSave:R,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(R,null,2).substring(0,1e3));const M=a?.scenarios.map(P=>!s&&P.name===e.name?{...P,name:h.name,description:h.description,metadata:{...P.metadata,data:R}}:P);s&&M.push({name:h.name,description:h.description,metadata:{data:R,interactiveExamplePath:a?.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",M),o&&await o(M,{recapture:I}),i&&i(h.name)},[a,e.name,h,y,s,o,i]),N=Z(S=>{p(A=>({...A,[S.target.name]:S.target.value}))},[]),w=Z(S=>{g(A=>{if(!A)return null;for(const I of[{arguments:S.metadata.data.argumentsData},S.metadata.data.mockData]){let R=I;for(const M of A.path)if(R=yn(R,M),!R)break;R&&(A.data=R)}return{...A}}),p({name:S.name,description:S.description,data:S.metadata.data})},[]),E=Z((S,A)=>{p(I=>{for(const R of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let M=R;for(const P of S.slice(0,-1))if(M=yn(M,P),!M)break;if(M){const P=M[S[S.length-1]];g(F=>F?(F.namedPath[F.namedPath.length-1]===P&&(F.namedPath[F.namedPath.length-1]=A.toString()),F.data[S[S.length-1]]=A,{...F}):null),M[S[S.length-1]]=A}}return{...I}})},[]),C=Z(S=>{if(S.length===0){g(null);return}let A=v;const I=[];let R=b;for(const M of S){if(I.push(isNaN(parseInt(M))?M:A[M]?.name??A[M]?.title??A[M]?.id??M),A=yn(A,M),!A){console.log("Data not found",A,M),g(null);return}Array.isArray(R)?R=R[0]:R=R[M]}g({path:S,namedPath:I,data:A,structure:R})},[v,b]);return G(()=>{const S=A=>{A.data.type==="codeyam-log"&&A.data.data?.includes("Error")&&console.error("[ScenarioEditor] Error from iframe:",A.data.data)};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]),G(()=>{if(l?.current?.contentWindow){const S={arguments:y.argumentsData??[],...y.mockData??{}},A={type:"codeyam-override-data",name:e.name,data:JSON.stringify(S)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:A.type,name:A.name,dataPreview:JSON.stringify(S).substring(0,200)+"...",fullData:S}),l.current.contentWindow.postMessage(A,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:S=>{x(S)},children:f?n(dr,{analysis:a,scenarioName:h.name,dataItem:f,onClick:C,onChange:E,onAIResult:w,onGenerateData:d,saveFeedback:m}):c(te,{children:[n(ur,{title:"Edit Name and Description",borderT:!0,children:n(gi,{scenarioFormData:h,handleInputChange:N})}),e.metadata.data&&n(ur,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(dr,{analysis:a,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:v,structure:b},onClick:C,onChange:E,onAIResult:w,onGenerateData:d,saveFeedback:m})})]})})};function mr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function Wn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0}){const o=ue(),[i,l]=k(null),[d,m]=k(!1),[u,h]=k(!1),[p,f]=k(!1),g=fe(!1),y=fe(null),v=fe(null),[b,x]=k(0),[N,w]=k(0),E=fe(null),C=fe(!1),{interactiveUrl:S,resetLogs:A}=Ue(a,s),I=fe(t);G(()=>{if(I.current!==t&&(I.current=t,y.current&&v.current&&r)){const M=mr(v.current),P=mr(r),F=y.current.replace(M,P);l(F),h(!0),f(!1),x(0),w(_=>_+1),C.current=!1,E.current&&(clearTimeout(E.current),E.current=null);return}},[t,r]),G(()=>{if(S){const M=S+"?width=600px";y.current=M,r&&(v.current=r),l(M),m(!1),h(!0)}},[S]),G(()=>{const M=P=>{P.data.type==="codeyam-resize"&&(C.current||(C.current=!0,E.current&&(clearTimeout(E.current),E.current=null),x(0),f(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h(!1)})})))};return window.addEventListener("message",M),()=>window.removeEventListener("message",M)},[]);const R=()=>{C.current=!1,E.current&&clearTimeout(E.current);const M=500*Math.pow(2,b);E.current=setTimeout(()=>{C.current||(b<2?(x(P=>P+1),w(P=>P+1),h(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),f(!0),h(!1)))},M)};return G(()=>{s&&!g.current&&t&&e&&(g.current=!0,m(!0),f(!1),l(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(P){console.error("[useInteractiveMode] Failed to clear log file:",P)}A(),o.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,A,a]),G(()=>{const M=e,P=()=>{if(g.current&&M){const _=new URLSearchParams({action:"stop",analysisId:M});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const T=navigator.sendBeacon("/api/interactive-mode",_);console.log("[useInteractiveMode] sendBeacon result:",T),T||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:_,keepalive:!0}).catch(L=>console.error("Failed to stop interactive mode:",L)))}},F=()=>{P()};return window.addEventListener("beforeunload",F),()=>{window.removeEventListener("beforeunload",F),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:M}),P()}},[e]),{interactiveServerUrl:i,isStarting:d,isLoading:u,showIframe:p,iframeKey:N,onIframeLoad:R}}function Gn({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=Ue(u??null,a||s);return r?c("div",{className:"flex-1 min-h-0 relative",children:[n("div",{style:{opacity:o?1:0},children:n(mi,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:m},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center gap-3",children:[n("div",{className:"w-12 h-12",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"})})}),c("div",{className:"text-center",children:[n("p",{className:"text-base font-semibold text-[#005c75] mb-1",children:a&&!r?"Starting interactive mode...":`Checking server stability. Attempt #${f+1}..`}),g&&!r&&n("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:g}),r&&f>0&&c("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:["Waiting for application to initialize... (attempt"," ",f+1,")"]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:s?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),g&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:g}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:s?"Loading the page in the background...":"Setting up the dev server for this scenario..."})]})})}const Ai=({data:e})=>[{title:e?.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Ei({params:e}){const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await cn(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=s.scenarios?.find(d=>d.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=s.scenarios?.find(d=>d.name===on),l=await Me();return D({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function _i(){const e=De(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=ct(),{iframeRef:l}=qn(),[d,m]=k(!1),[u,h]=k(null),[p,f]=k(null),[g,y]=k(!1),[v,b]=k(!1),[x,N]=k(null),{interactiveServerUrl:w,isStarting:E,isLoading:C,showIframe:S,iframeKey:A,onIframeLoad:I}=Wn({analysisId:t?.id,scenarioId:r?.id,scenarioName:r?.name,projectSlug:o,enabled:!0}),R=Z(async(_,T)=>{m(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",T),console.log("[EditScenario] Scenarios to save:",_);try{const L={analysis:t,scenarios:_};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:_.length,scenarioNames:_.map(O=>O.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)}),J=await Y.json();if(console.log("[EditScenario] API response:",J),!Y.ok||!J.success)throw new Error(J.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),T?.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),h("Changes saved. Capturing screenshot...");const O={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",O);const B=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});console.log("[EditScenario] Capture response status:",B.status);const H=await B.json();if(console.log("[EditScenario] Capture response body:",H),!B.ok||!H.success)throw console.error("[EditScenario] Capture failed:",H),new Error(H.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",H),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(T?.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const O=new FormData;O.append("analysisId",t.id||""),O.append("scenarioId",r.id||"");const B=await fetch("/api/recapture-scenario",{method:"POST",body:O}),H=await B.json();if(!B.ok||!H.success)throw new Error(H.error||"Failed to trigger recapture");console.log("Recapture queued:",H),f(H.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(L){console.error("Error saving scenarios:",L),h(`Error: ${L instanceof Error?L.message:String(L)}`)}finally{m(!1)}},[t,r.id,w]),M=Z(_=>{},[]),P=Z(async(_,T)=>{const L=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,existingScenarios:t.scenarios,scenariosDataStructure:t.metadata?.scenariosDataStructure,editingMockName:r.name,editingMockData:T?.data})}),Y=await L.json();if(!L.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),F=Z(async()=>{if(!r.id){N("Cannot delete scenario without ID");return}y(!0),N(null);try{const _=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:r.metadata?.screenshotPaths||[]})}),T=await _.json();if(!_.ok||!T.success)throw new Error(T.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(_){console.error("[EditScenario] Error deleting scenario:",_),N(_ instanceof Error?_.message:"Failed to delete scenario"),b(!1)}finally{y(!1)}},[r.id,r.metadata?.screenshotPaths,s,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(ee,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",t.entity?.name]})}),c("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Si,{currentScenario:r,defaultScenario:a,dataStructure:t.metadata?.scenariosDataStructure||{},analysis:t,shouldCreateNewScenario:!1,onSave:R,onNavigate:M,iframeRef:l,onGenerateData:P,saveFeedback:{isSaving:d,message:u,isError:u?.startsWith("Error")??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(ee,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),v?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>{F()},disabled:g,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:g?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>b(!1),disabled:g,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),x&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:x})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Gn,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:E,isLoading:C,showIframe:S,iframeKey:A,onIframeLoad:I,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Pi=Ie(function(){return n(un,{children:n(_i,{})})}),Mi=Object.freeze(Object.defineProperty({__proto__:null,default:Pi,loader:Ei,meta:Ai},Symbol.toStringTag,{value:"Module"})),ki=({data:e})=>[{title:e?.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Ti({params:e}){const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await cn(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=a.scenarios?.find(i=>i.name===on);if(!s)throw new Response("Default scenario not found",{status:404});const o=await Me();return D({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function Ii(){const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=De(),o=ct(),{iframeRef:i}=qn(),[l,d]=k(""),[m,u]=k(!1),[h,p]=k(!1),[f,g]=k(null),[y,v]=k(null),{interactiveServerUrl:b,isStarting:x,isLoading:N,showIframe:w,iframeKey:E,onIframeLoad:C}=Wn({analysisId:e?.id,scenarioId:t?.id,scenarioName:t?.name,projectSlug:s,enabled:!0}),S=Z(async()=>{if(!l.trim()){g("Please describe how you want to change the scenario");return}u(!0),g(null),v("Generating scenario with AI...");try{const I=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:e.metadata?.scenariosDataStructure})}),R=await I.json();if(!I.ok||!R.success)throw new Error(R.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",R.data);const M=R.data;if(!M.name||!M.data)throw new Error("AI response missing required fields (name or data)");v("Saving new scenario..."),p(!0);const P={name:M.name,description:M.description||l,metadata:{data:M.data,interactiveExamplePath:t.metadata?.interactiveExamplePath}},F=[...e.scenarios||[],P],_=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:F})}),T=await _.json();if(!_.ok||!T.success)throw new Error(T.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",T);const L=T.analysis?.scenarios?.find(Y=>Y.name===M.name);if(!L?.id){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),v("Scenario created! Redirecting..."),setTimeout(()=>o(`/entity/${a}`),1e3);return}if(b){v("Capturing screenshot...");const Y=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:b,scenarioId:L.id,projectId:e.projectId,viewportWidth:1440})}),J=await Y.json();!Y.ok||!J.success?(console.error("[CreateScenario] Capture failed:",J),v("Scenario created! (Screenshot capture failed)")):v("Scenario created and captured!")}else v("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${L.id}`)},1e3)}catch(I){console.error("[CreateScenario] Error:",I),g(I instanceof Error?I.message:String(I)),v(null)}finally{u(!1),p(!1)}},[l,e,t,a,b,o]),A=m||h;return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(ee,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",r?.name]})}),n("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:"Create New Scenario"}),n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:"Create a new scenario based on the Default Scenario"})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Describe how you'd like to change it to create your new scenario."})]}),c("div",{className:"flex-1",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"How would you like to change it for your new scenario?"}),n("textarea",{id:"prompt",value:l,onChange:I=>d(I.target.value),placeholder:"e.g., Show an empty state with no items in the list, or Display an error message when the API fails, or Show a user with admin privileges...",className:"w-full h-40 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:A})]}),c("div",{className:"mt-6 space-y-3",children:[n("button",{onClick:()=>{S()},disabled:A||!l.trim(),className:"w-full px-4 py-2 bg-[#005c75] text-white rounded-md text-sm font-medium hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors",children:A?"Creating...":"Create Scenario"}),y&&n("div",{className:"text-sm text-blue-600 bg-blue-50 px-3 py-2 rounded-md",children:y}),f&&n("div",{className:"text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:f})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Gn,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:b,isStarting:x,isLoading:N,showIframe:w,iframeKey:E,onIframeLoad:C,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Ri=Ie(function(){return n(un,{children:n(Ii,{})})}),ji=Object.freeze(Object.defineProperty({__proto__:null,default:Ri,loader:Ti,meta:ki},Symbol.toStringTag,{value:"Module"}));var V;(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={}))})(V||(V={}));function ma(e,t){return e?Object.values(V.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const ha=ma(process.env.DEFAULT_SMALLER_MODEL,V.Model.OPENAI_GPT4_1_MINI),$i=ma(process.env.DEFAULT_LARGER_MODEL,V.Model.OPENAI_GPT4_1),$e={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},xn={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Di={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},bn={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},ze={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Li={[V.Model.OPENAI_GPT5_1]:{id:V.Model.OPENAI_GPT5_1,provider:$e,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[V.Model.OPENAI_GPT5]:{id:V.Model.OPENAI_GPT5,provider:$e,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[V.Model.OPENAI_GPT5_MINI]:{id:V.Model.OPENAI_GPT5_MINI,provider:$e,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[V.Model.OPENAI_GPT5_NANO]:{id:V.Model.OPENAI_GPT5_NANO,provider:$e,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[V.Model.OPENAI_GPT4_1]:{id:V.Model.OPENAI_GPT4_1,provider:$e,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[V.Model.OPENAI_GPT4_1_MINI]:{id:V.Model.OPENAI_GPT4_1_MINI,provider:$e,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[V.Model.OPENAI_GPT4_O]:{id:V.Model.OPENAI_GPT4_O,provider:$e,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[V.Model.OPENAI_GPT4_O_MINI]:{id:V.Model.OPENAI_GPT4_O_MINI,provider:$e,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[V.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:V.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:xn,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[V.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:V.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:xn,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[V.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:V.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:xn,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[V.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:V.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Di,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[V.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:V.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:ze,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[V.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:V.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:ze,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[V.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:V.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:ze,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[V.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:V.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:ze,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[V.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:V.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:ze,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[V.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:V.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:bn,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[V.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:V.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:bn,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[V.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:V.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:bn,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[V.Model.PHIND_CODELLAMA]:{id:V.Model.PHIND_CODELLAMA,provider:$e,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[V.Model.GOOGLE_GEMINI_PRO]:{id:V.Model.GOOGLE_GEMINI_PRO,provider:ze,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[V.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:V.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:ze,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[V.Model.META_CODELLAMA_34B_INSTRUCT]:{id:V.Model.META_CODELLAMA_34B_INSTRUCT,provider:ze,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[V.Model.OPENAI_GPT4_PREVIEW]:{id:V.Model.OPENAI_GPT4_PREVIEW,provider:$e,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function mn(e){const t=Li[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Oi(e){return mn(e).maxCompletionTokens}function Fi(e){return mn(e).pricing}const hr=1e6;function Yi({model:e,usage:t}){const r=Fi(e);return r?t.prompt_tokens*(r.input/hr)+t.completion_tokens*(r.output/hr):null}function zi({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const a=t.usage||{prompt_tokens:0,completion_tokens:0},s=Yi({model:r,usage:a});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:s?Math.round(s*1e5)/1e5:void 0}}function Bi({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??ha,i=mn(o);Oi(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:a==="json_schema"&&s?{type:"json_schema",json_schema:{name:s.name,schema:s.schema,strict:s.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}Dn(jn);const Ot=new ws({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),pr={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Ft={};async function Pn({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=ha,attempts:i=0}){if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Ui(e,process.env.CODEYAM_LLM_FIXTURES_DIR);console.log(`CodeYam Debug: LLM Pool [queued=${Ot.size}, running=${Ot.pending}]`);const l=Date.now();let d,m=0;const u=mn(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new vs({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},g=Bi(f),y=await Ot.add(()=>(d=Date.now(),ar(()=>p.chat.completions.create(g,{timeout:300*1e3}),{...pr,onFailedAttempt:C=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:C,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})),{throwOnTimeout:!0}),v=Date.now(),b=zi({chatRequest:f,chatCompletion:y,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=m,b.wait_ms=d-l,b.duration_ms=v-l;const x=y.choices?.[0];let N=null;if(x){if(!x.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:y,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");N=x.message?.content}let w=N;N&&(w=N.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const E=a?w&&(w.match(/\{[\s\S]*\}/)?.[0]??w):w;if(!E){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:E,rawCompletion:N,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Pn({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(E.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:N,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(E)}catch(C){if(console.log("CodeYam Error: Invalid JSON in completion",{error:C.message,model:o,completion:E.substring(0,500),rawCompletion:N?.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:C.message});const S=`Your previous response contained invalid JSON with the following error:
57
+
58
+ ${C.message}
59
+
60
+ Here was your previous response:
61
+ \`\`\`
62
+ ${E}
63
+ \`\`\`
64
+
65
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,A=await Ot.add(()=>ar(()=>p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:E},{role:"user",content:S}]},{timeout:300*1e3}),{...pr,onFailedAttempt:P=>{console.log("CodeYam Error: Correction call failed",{error:P,attempts:i})}}),{throwOnTimeout:!0}),I=A.choices?.[0]?.message?.content;let R=I;I&&(R=I.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const M=R&&(R.match(/\{[\s\S]*\}/)?.[0]??R);if(!M)throw new Error("Correction attempt returned empty completion");try{JSON.parse(M),console.log("CodeYam: JSON correction successful");const P=Date.now();return b.duration_ms=P-l,{finishReason:A.choices[0].finish_reason,completion:M,stats:b}}catch(P){return console.log("CodeYam Error: Corrected JSON still invalid",{error:P.message,correctedCompletion:M.substring(0,500)}),await Pn({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${C.message}`)}return{finishReason:y.choices[0].finish_reason,completion:E,stats:b}}async function Ui(e,t){const r=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!r.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 s=r.readdirSync(t).filter(h=>h.endsWith(".json"));if(s.length===0)throw new Error(`No LLM fixture files found in ${t}`);const o={};for(const h of s)try{const p=r.readFileSync(a.join(t,h),"utf-8"),f=JSON.parse(p);o[f.prompt_type]||(o[f.prompt_type]=[]),o[f.prompt_type].push(f)}catch(p){console.warn(`Failed to parse LLM fixture file ${h}:`,p)}const i=o[e];if(!i||i.length===0){const h=Object.keys(o).join(", ");throw new Error(`No captured LLM call found for type '${e}'. Available types: ${h}`)}const l=`${t}::${e}`;Ft[l]||(Ft[l]=0);const d=Ft[l];Ft[l]=(d+1)%i.length;const m=i[d];console.log(`CodeYam Test: Replaying LLM response for '${e}' [${d+1}/${i.length}]`);let u;try{u=JSON.parse(m.response).choices?.[0]?.message?.content||m.response}catch{u=m.response}return{finishReason:"stop",completion:u,stats:{model:m.model??"fixture",prompt_type:e,system_message:m.system_message??"",prompt_text:m.prompt_text??"",response:m.response??"",input_tokens:m.input_tokens??0,output_tokens:m.output_tokens??0,cost:m.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(s){throw console.error("CodeYam Test Error: Failed to replay LLM call:",s),s}}function fr(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function qi(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=At(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let l;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?l=K.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=K.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const u=K.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:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=fr();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new sn().send(new Cs({TableName:fr(),Item:Ss(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new sn({});new sn({});new sn({});const Wi=3,Gi=2,Hn=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Wi*String(t).length*(1+Gi)});new Ln(Hn());new Ln(Hn());new Ln(Hn());class Hi{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){return this.byClassAndMethod.get(t)?.get(r)}}class Ki{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Vi{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ji{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];if(a.addType(o,"function"),a.addEquivalence(o.withParameter(1),r.withElement("*")),s.args.length>1){const i=s.args[1];a.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class Qi{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addType(t,"array"),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Zi{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.withReturnValues();a.addType(s,"array")}isComplete(){return!0}}class Xi{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>2)for(let o=2;o<s.args.length;o++){const i=s.args[o];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class el{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class tl{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class nl{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class rl{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class al{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class sl{getReturnType(){return"object"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"array")}}isComplete(){return!0}}class ol{getReturnType(){return"unknown"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class il{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class ll{getReturnType(){return"array"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function cl(){const e=new Hi;return e.register("filter",new Ki,"Array"),e.register("map",new tl,"Array"),e.register("flatMap",new nl,"Array"),e.register("join",new el,"Array"),e.register("find",new Vi,"Array"),e.register("findLast",new al,"Array"),e.register("at",new rl,"Array"),e.register("reduce",new Ji,"Array"),e.register("concat",new Qi,"Array"),e.register("slice",new Zi,"Array"),e.register("splice",new Xi,"Array"),e.register("fromEntries",new sl,"Object"),e.register("then",new ol,"Promise"),e.register("useState",new ll,"React"),e.register("useMemo",new il,"React"),e}cl();class dl{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const s=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${o}${s}${r}`,JSON.stringify(a)):console.info(`${o}${s}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new dl({enabled:!1});const ul=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),ml=new Set(["find","at","pop","shift"]),hl=new Set(["map","reduce","flatMap","concat","join","some"]),pl=new Set([...ul,...ml,...hl]),fl=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),gl=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),yl=new Set([...fl,...gl]);[...pl,...yl];new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));function pa(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 Ns.parse(e)}catch(r){const s=r.message.match(/invalid character .* at (\d+):(\d+)/);if(s){const o=parseInt(s[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),pa(e)}return null}}function xl({description:e,existingScenarios:t,scenariosDataStructure:r}){return`Mock Scenario Data Structure:
66
+ \`\`\`
67
+ ${JSON.stringify(r,null,2)}
68
+ \`\` Existing Mock Scenario Data:
69
+ \`\`\`
70
+ ${JSON.stringify(t,null,2)}
71
+ \`\`\`
72
+ New Scenario user-created prompt: "${e}"
73
+ `}function bl({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===on);return`Mock Scenario Data Structure:
74
+ \`\`\`
75
+ ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
76
+ \`\`\`
77
+
78
+ Existing Mock Scenario Data:
79
+ \`\`\`
80
+ ${JSON.stringify(a.map(i=>({name:i.name,data:En(o.metadata.data,i.metadata.data)})),null,2)}
81
+ \`\`\`
82
+
83
+ Mock Scenario that should be edited: "${t}"
84
+ ${r?`The portion of the data that should be edited:
85
+ \`\`\`
86
+ ${JSON.stringify(r,null,2)}
87
+ \`\`\``:""}
88
+
89
+ How this data should be changed: "${e}"
90
+ `}async function vl({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:o}){const i=t?bl({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):xl({description:e,existingScenarios:a,scenariosDataStructure:s}),l=await Pn({type:"guessScenarioDataFromDescription",systemMessage:t?Cl(r):wl,prompt:i,model:o??$i});await qi({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:o},...l.stats});const{completion:d}=l;return d?pa(d):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const wl=`
91
+ 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.
92
+
93
+ 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.
94
+
95
+ 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.
96
+
97
+ You must respond with valid JSON following this format of this TS type definition:
98
+ \`\`\`
99
+ export type ScenarioData = {
100
+ name: string;
101
+ description: string;
102
+ data: {
103
+ mockData: { [key: string]: unknown };
104
+ argumentsData: { [key: string]: unknown };
105
+ };
106
+ };
107
+
108
+ \`\`\`
109
+ `,Cl=e=>`
110
+ 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.
111
+
112
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
113
+ ${e?`
114
+ 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.`:""}
115
+
116
+ 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.
117
+
118
+ You must respond with valid JSON following this type definition:
119
+ \`\`\`
120
+ {
121
+ data: {
122
+ mockData: { [key: string]: unknown };
123
+ argumentsData: { [key: string]: unknown };
124
+ }
125
+ }
126
+ \`\`\`
127
+ `;async function Nl({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i}=t;if(!r)return D({error:"Missing required field: description"},{status:400});const l=await vl({description:r,existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i});return D({success:!0,data:l})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),D({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Sl=Object.freeze(Object.defineProperty({__proto__:null,action:Nl},Symbol.toStringTag,{value:"Module"}));async function Al(e,t){const r=ie();if(!r)return{entityCalls:[],analysisCalls:[]};const a=K.join(r,".codeyam","llm-calls");try{await ve.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const l=(await ve.readdir(a)).filter(b=>b.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],h=[];for(const b of l)b.startsWith(d)||m&&b.startsWith(m)?u.push(b):h.push(b);const p=u.map(async b=>{try{const x=K.join(a,b),N=await ve.readFile(x,"utf-8");return JSON.parse(N)}catch{return null}}),f=h.map(async b=>{try{const x=K.join(a,b),N=await ve.readFile(x,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),v=[...g,...y].filter(b=>b!==null);for(const b of v)b.object_id===e?s.push(b):t&&b.object_id===t&&o.push(b);s.sort((b,x)=>x.created_at-b.created_at),o.sort((b,x)=>x.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function El({params:e,request:t}){const{entitySha:r}=e;if(!r)return D({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Al(r,s);return D(o)}const _l=Object.freeze(Object.defineProperty({__proto__:null,loader:El},Symbol.toStringTag,{value:"Module"}));function Pl(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ne("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Ml(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Ml(e){const t=e.trim().split(`
128
+ `).filter(a=>a.length>0),r=[];for(const a of t){const s=a[0],o=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),l,d=!1,m;if(s==="A"||o==="A")l="added",d=s==="A";else if(s==="M"||o==="M")l="modified",d=s==="M";else if(s==="D"||o==="D")l="deleted",d=s==="D";else if(s==="R"||o==="R"){l="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=le.join(u,i);try{const p=(g,y)=>{const v=Ve.readdirSync(g,{withFileTypes:!0}),b=[];for(const x of v){const N=le.join(g,x.name),w=le.relative(u,N);x.isDirectory()?b.push(...p(N,y)):x.isFile()&&b.push(w)}return b},f=p(h,u);for(const g of f)r.push({path:g,status:l,staged:d,...m&&{oldPath:m}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...m&&{oldPath:m}})}return r}function kl(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ne("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 Tl(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Ne('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return Ne("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ne("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 Il(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ne('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
129
+ `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function fa(){const e=ie();return e?Pl(e):[]}function Rl(){const e=ie();return e?kl(e):null}function jl(){const e=ie();return e?Tl(e):"main"}function $l(){const e=ie();return e?Il(e):[]}function ga(e,t){const r=ie();return r?Dl(e,t,r):[]}function Dl(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ne(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
130
+ `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let m=l[1],u,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",u=l[1],m=l[2]):h="modified",{path:m,status:h,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function Ll(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Ne(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=Ve.readFileSync(le.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),s=""}return{oldContent:a,newContent:s,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Ol(e){const t=ie();return t?Ll(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Fl(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Ne(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Ne(`git show ${r}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Gt(e,t,r){const a=ie();return a?Fl(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function gr(e,t){try{return Ne(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]})?.toString()?.trim()??null}catch(r){return console.error(`Failed to get commit SHA for ${e}:`,r),""}}function Yl(e,t,r,a){const s=Rn.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function ya(){const e=ie();if(!e)throw new Error("No project root found");const t=le.join(e,".codeyam","cache","branch-entity-diff");return Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0}),t}function zl(e){try{const t=ya(),r=le.join(t,`${e}.json`);if(!Ve.existsSync(r))return null;const a=Ve.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Bl(e,t){try{const r=ya(),a=le.join(r,`${e}.json`);Ve.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Ul(e,t,r){const a=Jt(t,e),s=Jt(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),l=[],d=[],m=[];for(const[u,h]of i){const p=o.get(u);p?p.sha!==h.sha&&d.push({name:u,baseSha:p.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[u,h]of o)i.has(u)||m.push(h);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:m}}function ql(e,t){const r=ie();if(!r)throw new Error("No project root found");const a=gr(e,r),s=gr(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Yl(e,t,a,s),i=zl(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=ga(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=Gt(u.path,e,t),p=Jt(h.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const h=Gt(u.path,e,t),p=Jt(h.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=Gt(u.path,e,t),p=Ul(u.path,h.oldContent,h.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const m={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Bl(o,m),m}function Wl({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return D({error:"Missing required parameters: base and compare"},{status:400});const s=ql(r,a);return D(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),D({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Gl=Object.freeze(Object.defineProperty({__proto__:null,loader:Wl},Symbol.toStringTag,{value:"Module"}));async function Hl({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:s,viewportWidth:o=1440}=t;if(!r||!a||!s)return D({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=ie();if(!i)return D({error:"Project root not found"},{status:500});const l=K.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),m=await new Promise(p=>{const f=K.join(i,".codeyam","db.sqlite3"),g=$n("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",v="";g.stdout.on("data",b=>{const x=b.toString();y+=x;const N=x.trim().split(`
131
+ `);for(const w of N)w.includes("[Capture]")&&console.log(w)}),g.stderr.on("data",b=>{const x=b.toString();v+=x,console.error("[Capture:Error]",x.trim())}),g.on("close",b=>{p(b===0?{success:!0,output:y}:{success:!1,output:y,error:v||`Process exited with code ${b}`})}),g.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),p({success:!1,output:"",error:b.message})})});if(!m.success)return D({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return D({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return D(h)}catch(t){return console.error("[Capture] Error:",t),D({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Kl=Object.freeze(Object.defineProperty({__proto__:null,action:Hl},Symbol.toStringTag,{value:"Module"}));async function Vl(e,t,r){console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Ae();const a=await qe({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ce(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i?.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${a.scenarios?.length||0} scenarios`),await Pt(e,f=>{if(f&&(f.readyToBeCaptured=!0,f.scenarios))for(const g of f.scenarios)delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=ie();if(!d)throw new Error("Project root not found");const m=K.join(d,".codeyam","config.json"),u=JSON.parse(W.readFileSync(m,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Jl(e,t,r){console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Ae();const a=await qe({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=a.scenarios?.find(u=>u.id===t);if(!s)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${s.name}`),await Pt(e,u=>{if(u&&(u.readyToBeCaptured=!0,u.scenarios)){const h=u.scenarios.find(p=>p.name===s.name);h&&(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 ${s.name} for recapture`);const o=ie();if(!o)throw new Error("Project root not found");const i=K.join(o,".codeyam","config.json"),l=JSON.parse(W.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}function tn(e){return K.join(e,".codeyam","queue.json")}function vt(e){const t=tn(e);if(!W.existsSync(t))return{paused:!1,jobs:[]};try{const r=W.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Ql(e,t){const r=tn(e),a=K.dirname(r);W.existsSync(a)||W.mkdirSync(a,{recursive:!0});try{W.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function Zl({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){return new Promise((i,l)=>{const d=e.endsWith("/")?e:`${e}/`,m=t.endsWith("/")?t:`${t}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...o);for(const f of r)u.push(`--exclude=${f}`);u.push(d,m);const h=Date.now(),p=$n("rsync",u);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-h)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),l(f)})})}const Xl=Dn(jn);async function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(e){try{return process.kill(e,0),!0}catch{return!1}}async function xa(e){try{const{stdout:t}=await Xl(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
132
+ `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await xa(s);a.push(...o)}return a}catch{return[]}}function yr(e,t,r){try{process.kill(e,t)}catch(a){r?.(`Error sending ${t} to process ${e}: ${a}`)}}async function nc(e,t,r){const a=await xa(e);for(const s of a.reverse())await yr(s,t,r);await yr(e,t,r)}async function nn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function s(o,i){await nc(e,o,t);for(let l=0;l<i;l++)if(await ec(1e3),a+=1e3,!await tc(e))return t(`Process tree ${e} successfully killed with ${o} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await s("SIGINT",5)||await s("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await s("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function rc(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??=[],e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ts(),createdAt:t}}As.config({quiet:!0});var ba=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ba||{});class ac extends Es{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Ps(),{process:a,type:s,name:o,metadata:i,parentId:l}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const m=(h,p)=>{this.handleProcessExit(r,h,p)},u=h=>{this.handleProcessError(r,h)};return a.on("exit",m),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",m),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(l=>this.shutdown(l,r))),o.pid)try{await nn(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),s.state==="running"&&(s.state="killed",s.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(s=>this.shutdown(s.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[s,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(s)}}}handleProcessExit(t,r,a){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.exitCode=r,o.signal=a,r===0?o.state="completed":a?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:s}=a;s.endedAt=Date.now(),s.state="failed",s.metadata={...s.metadata,error:r.message},this.emit("processExited",s)}}let vn=null;function sc(){return vn||(vn=new ac),vn}const oc={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function ic({command:e,args:t,workingDir:r,outputOptions:a=oc,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},l=$n(e,t,{cwd:r,env:i});return sc().register({process:l,type:ba.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const g=le.join(r,"log.txt");W.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
133
+ `).map(b=>b.trim()?`[${y}]${g} ${b}`:b).join(`
134
+ `)};l.stdout.on("data",function(f){const g=f?.toString()??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&h(y+`
135
+ `),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=f?.toString()??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&h(y+`
136
+ `),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function lc(e){const t=[];return Object.keys(e).forEach(r=>{const a=e[r];a!==void 0&&(typeof a=="boolean"?a&&t.push(`--${r}`):a!==null&&t.push(`--${r}`,String(a)))}),t}function cc({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
137
+ `);W.writeFileSync(`${e}/.env`,s);const o=lc(r);return ic({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const dc=K.dirname(zr(import.meta.url));function uc(e){let t=e;for(;t!==K.dirname(t);){const r=K.join(t,"package.json");if(W.existsSync(r))try{if(JSON.parse(W.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=K.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Kn(){const e=uc(dc);return K.join(e,"analyzer-template")}function pt(e){return`/tmp/codeyam/local-dev/${e}/codeyam`}function mc(e){return`/tmp/codeyam/local-dev/${e}/project`}async function xr(e){const t=Kn(),r=pt(e);if(!W.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await ve.mkdir(K.dirname(r),{recursive:!0}),await Zl({sourcePath:t,destinationPath:r,silent:!0})}function hn(e,t,r,a){const s=pt(e);if(!W.existsSync(s))throw new Error(`Analyzer not found at ${s}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return cc({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function hc(e){const t=Kn(),r=pt(e),a=K.join(t,".build-info.json"),s=K.join(r,".build-info.json");if(!W.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!W.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!W.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(W.readFileSync(a,"utf8")),i=JSON.parse(W.readFileSync(s,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function pc(e,t){const r=pt(e);if(!W.existsSync(r)){t.update("Creating analyzer..."),await xr(e);return}const a=hc(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await xr(e))}async function va(e){const t=mc(e);if(!W.existsSync(t))return;const r=K.join(t,".sync-metadata.json");W.existsSync(r)&&await ve.unlink(r);const a=K.join(t,"__codeyamMocks__");W.existsSync(a)&&await ve.rm(a,{recursive:!0})}const fc=K.dirname(zr(import.meta.url));function wa(){let e=fc;for(;e!==K.dirname(e);){const t=K.join(e,"package.json");if(W.existsSync(t))try{if(JSON.parse(W.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=K.dirname(e)}return null}function gc(){const e=wa();return e?K.join(e,"package.json"):null}function Ht(e){if(!W.existsSync(e))return null;try{return JSON.parse(W.readFileSync(e,"utf8"))}catch{return null}}function Ca(e){let t="unknown";const r=wa(),a=gc();if(a)try{t=JSON.parse(W.readFileSync(a,"utf8")).version||"unknown"}catch{}let s=null;if(r){const u=[K.join(r,"src/webserver/build-info.json"),K.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const h of u)if(s=Ht(h),s)break}const o=Kn(),i=K.join(o,".build-info.json"),l=Ht(i);let d=null;if(e){const u=pt(e),h=K.join(u,".build-info.json");d=Ht(h)}let m=!1;return l&&d?m=l.buildTime>d.buildTime:l&&!d&&e&&(m=!0),{cliVersion:t,webserverVersion:s,templateVersion:l,cachedAnalyzerVersion:d,isCacheStale:m}}function Na(e){const t=pt(e),r=K.join(t,".build-info.json");return Ht(r)?.version??null}class yc extends _s{watcher=null;dbPath=null;isWatching=!1;async start(){if(!this.isWatching)try{this.dbPath=ht();const{default:t}=await import("chokidar"),r=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=t.watch(r,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const s=Date.now(),o=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${o} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:s})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(t){console.error("Failed to start database watcher:",t),this.emit("error",t)}}notifyChange(t="unknown"){const r=Date.now(),a=new Date(r).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${t}`),console.log(`[dbNotifier] Timestamp: ${a} (${r})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:t,timestamp:r})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const st=new yc;async function xc(e,t){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await bc(e,t);else if(e.type==="recapture")await vc(e,t);else if(e.type==="debug-setup")await wc(e,t);else if(e.type==="interactive-start")await Cc(e,t);else if(e.type==="interactive-stop")await Nc(e,t);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(r){throw console.error(`[Queue] Job ${e.id} failed:`,r),r}}async function bc(e,t){const{projectSlug:r,commitSha:a,entityShas:s}=e;if(!a)throw new Error("Analysis job missing commitSha");const o=s||[],{project:i}=await Te(r);await va(r),await pc(r,{update:g=>console.log(`[Queue] ${g}`)});const l=Na(r),d={...await mt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ht(),...o.length>0?{ENTITY_SHAS:o.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...l?{ANALYZER_VERSION:l}:{}},m=i.metadata?.webapps?.[0];if(!m)throw new Error("No webapps found in project metadata");const u=e.onlyDataStructure,h={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:0,noServer:!0,framework:m.framework,...u?{}:{orchestrateCapture:"local-sequential"}},p=hn(r,d,h),f=g=>{try{return process.kill(g,0),!0}catch{return!1}};await at({commitSha:a,runStatusUpdate:{currentEntityShas:o,entityCount:o.length||e.filePaths?.length||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:p.process.pid}}),st.notifyChange("commit");try{try{const g=new Promise((y,v)=>setTimeout(()=>v(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([p.promise,g]),await at({commitSha:a,runStatusUpdate:{analyzerPid:void 0},archiveCurrentRun:!0}),st.notifyChange("commit"),await at({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),st.notifyChange("commit"),await new Promise(y=>setTimeout(y,2e3))}finally{if(p.process.pid)try{f(p.process.pid)&&await nn(p.process.pid,()=>{})}catch{}}}catch(g){if(console.error(`[Queue] Analysis job ${e.id} failed:`,g),p.process.pid&&f(p.process.pid))try{await nn(p.process.pid,()=>{})}catch{}try{await at({commitSha:a,runStatusUpdate:{analyzerPid:void 0,failedAt:new Date().toISOString(),failureReason:g instanceof Error?g.message:String(g)}}),st.notifyChange("commit")}catch(y){console.error("[Queue] Failed to update commit metadata after job failure:",y)}throw g}}async function vc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s,defaultWidth:o}=e;if(!a)throw new Error("Recapture job missing analysisId");const i=await qe({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);if(o){const{getDatabase:p}=await import("./index-D4JpXSIO.js"),f=p(),g=await f.selectFrom("entities").select(["metadata"]).where("sha","=",i.entitySha).executeTakeFirst();let y={};g?.metadata&&(typeof g.metadata=="string"?y=JSON.parse(g.metadata):y=g.metadata),y.defaultWidth=o,await f.updateTable("entities").set({metadata:JSON.stringify(y)}).where("sha","=",i.entitySha).execute()}await Pt(a,p=>{if(p.readyToBeCaptured=!0,p.scenarios)for(const f of p.scenarios)(!s||f.name===s)&&(delete f.screenshotStartedAt,delete f.screenshotFinishedAt,delete f.interactiveStartedAt,delete f.interactiveFinishedAt,delete f.error,delete f.errorStack)});const{project:l}=await Te(r),d=Na(r),m={...await mt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ht(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...s?{SCENARIO_IDS:s}:{},...d?{ANALYZER_VERSION:d}:{}},u={packageManager:l.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!0,framework:l.metadata?.webapps?.[0]?.framework??_t.Next,orchestrateCapture:"local-sequential"},h=hn(r,m,u);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function wc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s}=e;if(!a)throw new Error("Debug setup job missing analysisId");const o=await qe({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o||!o.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Te(r);await va(r);const l={...await mt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:o.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ht(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};s&&(l.SCENARIO_IDS=s);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||_t.Next},u=await hn(r,l,d).promise;if(u!==0)throw new Error(`Prep process exited with code ${u}`)}async function Cc(e,t){const{projectSlug:r,analysisId:a,scenarioId:s}=e;if(!a)throw new Error("Interactive start job missing analysisId");const o=await qe({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o||!o.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Te(r),l={...await mt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:o.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ht(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};s&&(l.SCENARIO_IDS=s);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:`/tmp/codeyam/local-dev/${r}/project`,port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||_t.Next};await Pt(a,u=>{u.readyToBeCaptured=!0});const m=hn(r,l,d);await Zr(a,u=>{u.interactiveMode={pid:m.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${m.process.pid}`)}async function Nc(e,t){const{projectSlug:r,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const s=await qe({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${a} not found`);const o=s.metadata?.interactiveMode;if(!o?.pid){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const i=o.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${i}`);try{try{process.kill(i,0)}catch{console.log(`[Queue] Process ${i} already exited`);return}await nn(i,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${i}`)}catch(l){throw console.error(`[Queue] Failed to kill process ${i}:`,l),l}finally{await Zr(a,l=>{l.interactiveMode=null})}}class Sc{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},this.onStateChange=r}start(){this.state=vt(this.projectRoot),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||At(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}async processNext(){if(this.state.paused||this.processing||this.state.jobs.length===0)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 xc(t,this.projectRoot),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`)}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?.message||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>{this.processNext()})}}save(){Ql(this.projectRoot,this.state),this.onStateChange&&this.onStateChange()}}class Ac{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=tn(this.projectRoot);if(!W.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=tn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=W.watch(r,(a,s)=>{s==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=W.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 Ec{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=vt(r)}start(){this.cachedState=vt(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 Ac(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const s=new Promise((i,l)=>{r=i,a=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:o,completion:s}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=vt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=vt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function _c(e){const t=K.join(e,".codeyam","server.json");if(!W.existsSync(t))return null;try{const r=W.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Pc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Mc(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}async function kc(e){const t=_c(e);return!t||!Pc(t.pid)||!await Mc(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}let wt=null,Yt=null;async function Tc(){if(!wt){if(Yt){await Yt;return}Yt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Xr()||process.cwd();Ho(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await kc(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Ec(t,e,()=>{st.notifyChange("unknown")});await r.start(),wt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Sc(e,()=>{st.notifyChange("unknown")});await r.start(),wt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Yt}}async function Ye(){return wt||await Tc(),wt}async function Ic({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ye()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return D({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await Jl(s,o,r);return console.log("[API] Scenario recapture queued",i),D({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),D({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Rc=Object.freeze(Object.defineProperty({__proto__:null,action:Ic},Symbol.toStringTag,{value:"Module"}));async function jc({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const a=`/tmp/codeyam/local-dev/${r}/codeyam/log.txt`;try{return await fs(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error clearing log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function $c({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=`/tmp/codeyam/local-dev/${t}/codeyam/log.txt`;try{if(!ls(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const a=await gs(r,"utf-8");return!a||a.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error reading log file:",a);const s=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Dc=Object.freeze(Object.defineProperty({__proto__:null,action:jc,loader:$c},Symbol.toStringTag,{value:"Module"}));async function Lc(e,t){console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Ae();const r=await qe({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=r.scenarios?.find(o=>o.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={returnValue:{status:"success",data:a.metadata?.data?.argumentsData?.[0]||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify(a.metadata?.data?.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function Oc({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return D({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Lc(r,a);return console.log("[API] Function execution completed successfully"),D({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),D({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Fc=Object.freeze(Object.defineProperty({__proto__:null,action:Oc},Symbol.toStringTag,{value:"Module"}));function Yc({request:e}){return D({status:"ok"})}async function zc({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ye()),!r)return console.error("[Interactive Mode API] Queue not initialized"),D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("action"),o=a.get("analysisId"),i=a.get("scenarioId");if(!s||!o)return D({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return D({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Me();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return D({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return D({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return D({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),D({error:"Failed to control interactive mode",details:s},{status:500})}}const Bc=Object.freeze(Object.defineProperty({__proto__:null,action:zc,loader:Yc},Symbol.toStringTag,{value:"Module"}));async function Uc({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:a}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),a&&a.length>0){const s=ie();if(s)for(const o of a){const i=le.join(s,".codeyam","captures","screenshots",o);try{await ge.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}return await wo({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const qc=Object.freeze(Object.defineProperty({__proto__:null,action:Uc},Symbol.toStringTag,{value:"Module"})),Kt="/tmp/codeyam",br=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Sa=200,Wc=Sa*1024*1024;function rt(e,t){try{return Ne(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function vr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Gc(e){return rt("config user.email",e)}function Hc(e,t=20){const r=K.join(Kt,"local-dev",e,"codeyam","log.txt");if(!W.existsSync(r))return[];try{return W.readFileSync(r,"utf8").split(`
138
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}function Kc(e){const{projectRoot:t,projectSlug:r,outputPath:a,feedback:s,screenshot:o,onProgress:i}=e,l=i||(()=>{});l("Gathering metadata...");const d=rt("rev-parse HEAD",t)||"unknown",m=rt("rev-parse --abbrev-ref HEAD",t)||"unknown",u=rt("status --porcelain",t),h=rt("remote get-url origin",t),p=u!==null&&u.length>0,f=Ca(r),g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:d,branch:m,isDirty:p,remoteUrl:h},versions:{cli:f.cliVersion,webserver:f.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:s};l("Preparing report...");const y=rt("ls-files --cached --others --exclude-standard",t);if(y===null)throw new Error("Could not run git ls-files. Is this a git repository?");const v=new Set(y.split(`
139
+ `).filter(Boolean));v.add(".codeyam"),v.add(".git");const b=Date.now(),x=K.join(Kt,`report-staging-${b}`),N=K.join(x,"report"),w=K.join(N,"project");W.mkdirSync(w,{recursive:!0});try{for(const I of v){const R=K.join(t,I),M=K.join(w,I);if(W.existsSync(R)){const P=K.dirname(M);W.mkdirSync(P,{recursive:!0}),W.statSync(R).isDirectory()?W.cpSync(R,M,{recursive:!0}):W.copyFileSync(R,M)}}W.writeFileSync(K.join(N,"report-meta.json"),JSON.stringify(g,null,2));const E=K.join(Kt,"local-dev",r,"codeyam","log.txt");W.existsSync(E)?W.copyFileSync(E,K.join(N,"codeyam-log.txt")):W.writeFileSync(K.join(N,"codeyam-log.txt"),`# Log file not found
140
+ `),o&&o.length>0&&(W.writeFileSync(K.join(N,"screenshot.jpg"),o),l(`Screenshot included (${vr(o.length)})`)),l("Creating archive...");const C=K.join(Kt,`report-${r}-${b}.tar.gz`),S=a||C;try{Ne(`tar -czf "${S}" -C "${x}" report`,{stdio:"pipe"})}catch(I){throw new Error(`tar failed: ${I.message}`)}const A=W.statSync(S);if(A.size>Wc)throw W.unlinkSync(S),new Error(`Report too large: ${vr(A.size)} (max: ${Sa} MB). Try removing large files from the project or adding them to .gitignore`);return{path:S,metadata:g,size:A.size}}finally{W.rmSync(x,{recursive:!0,force:!0})}}async function Vc(e){const{archivePath:t,projectSlug:r,metadata:a,onProgress:s}=e,o=s||(()=>{}),i=W.statSync(t);o("Requesting upload URL...");const l=await fetch(`${br}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:r,fileSizeBytes:i.size,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!l.ok){const f=await l.json();throw new Error(f.error||`Server returned ${l.status}`)}const{reportId:d,uploadUrl:m}=await l.json();o("Uploading report...");const u=W.readFileSync(t),h=await fetch(m,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:u});if(!h.ok)throw new Error(`Upload failed: ${h.status}`);o("Confirming upload...");const p=await fetch(`${br}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:d})});if(!p.ok){const f=await p.json();throw new Error(f.error||`Confirm failed: ${p.status}`)}return{reportId:d}}async function Jc({request:e}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),s=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("screenshot");let h;if(u&&u.size>0){const b=await u.arrayBuffer();h=Buffer.from(b),console.log(`[Report] Screenshot received: ${u.size} bytes`)}const p=ie();if(!p)return D({error:"Project root not found"},{status:500});const f=await Me();if(!f)return D({error:"Project slug not found"},{status:500});const g={issueType:r||"other",description:a||void 0,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:Hc(f,20)};console.log(`[Report] Generating report for ${f}...`),console.log(`[Report] Context: ${g.source}, issue: ${g.issueType}`);const y=await Kc({projectRoot:p,projectSlug:f,feedback:g,screenshot:h,onProgress:b=>{console.log(`[Report] ${b}`)}});console.log(`[Report] Archive created: ${y.path} (${y.size} bytes)`);const v=await Vc({archivePath:y.path,projectSlug:f,metadata:y.metadata,onProgress:b=>{console.log(`[Report] ${b}`)}});return console.log(`[Report] Upload complete: ${v.reportId}`),D({success:!0,reportId:v.reportId,size:y.size})}catch(t){return console.error("[Report] Error:",t),D({error:t.message||"Failed to generate report"},{status:500})}}function Qc(){const e=ie(),t=e?Gc(e):null;return D({defaultEmail:t})}const Zc=Object.freeze(Object.defineProperty({__proto__:null,action:Jc,loader:Qc},Symbol.toStringTag,{value:"Module"})),wr=Dn(jn);async function Xc({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const a=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const s=await Promise.all(a.map(async o=>{const i=ed(o),l=i?await td(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:s})}function ed(e){try{return process.kill(e,0),!0}catch{return!1}}async function td(e){try{const{stdout:t}=await wr(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await wr(`ps -p ${e} -o args=`),a=r.trim(),s=a.match(/codeyam-(\w+)/);return s?`codeyam-${s[1]}`:a.split(" ")[0]||null}catch{return null}}}const nd=Object.freeze(Object.defineProperty({__proto__:null,loader:Xc},Symbol.toStringTag,{value:"Module"}));async function rd({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((l,d)=>{const m=l.metadata?.data?.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!l.metadata?.data,mockDataKeys:l.metadata?.data?.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const s=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await Oo(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{const m=l.metadata?.data?.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const ad=Object.freeze(Object.defineProperty({__proto__:null,action:rd},Symbol.toStringTag,{value:"Module"}));async function sd({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:s}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Cr(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,l)),m=Cr(r);if(m){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(s)try{await at({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Cr(e){try{return process.kill(e,0),!0}catch{return!1}}const od=Object.freeze(Object.defineProperty({__proto__:null,action:sd},Symbol.toStringTag,{value:"Module"}));async function id({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=ie();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=le.join(r,".codeyam","captures","screenshots",t);try{await ge.access(a);const s=await ge.readFile(a),o=le.extname(a).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(s,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const ld=Object.freeze(Object.defineProperty({__proto__:null,loader:id},Symbol.toStringTag,{value:"Module"}));function cd(e){const t=Date.now(),r=new Date(e).getTime(),a=t-r,s=Math.floor(a/6e4),o=Math.floor(s/60);return s<1?"just now":s<60?`${s}m ago`:o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function dd({state:e,currentRun:t}){ue();const r=t?.currentEntityShas&&t.currentEntityShas.length>0;return!e.currentlyExecuting&&(!e.jobs||e.jobs.length===0)?null:c("div",{className:"bg-white border-2 rounded-xl shadow-lg p-5 mb-6",style:{borderColor:"#005C75"},children:[e.currentlyExecuting&&!r&&c("div",{className:"mb-4 border-2 rounded-lg p-3",style:{backgroundColor:"#e8f1f5",borderColor:"#005C75"},children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(ot,{size:20,className:"animate-spin",style:{color:"#005C75"}}),n("span",{className:"text-sm font-bold",style:{color:"#003d52"},children:"Starting analysis..."})]}),c("p",{className:"text-xs mb-2",style:{color:"#004a5e"},children:["Booting analyzer for"," ",e.currentlyExecuting.entities?.length||e.currentlyExecuting.entityShas?.length||1," ",(e.currentlyExecuting.entities?.length||e.currentlyExecuting.entityShas?.length)===1?"entity":"entities"]}),e.currentlyExecuting.entities&&e.currentlyExecuting.entities.length>0&&c("div",{className:"space-y-1 mt-2 max-h-[100px] overflow-y-auto bg-white rounded-md p-2 border",style:{borderColor:"#b3d9e6"},children:[e.currentlyExecuting.entities.slice(0,3).map(a=>c(ee,{to:`/entity/${a.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate",title:`${a.name} - ${a.filePath}`,style:{color:"#005C75"},onMouseEnter:s=>s.currentTarget.style.color="#003d52",onMouseLeave:s=>s.currentTarget.style.color="#005C75",children:[n(Oe,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[a.name,c("span",{className:"text-gray-400 ml-1",children:["(",a.filePath,")"]})]})]},a.sha)),e.currentlyExecuting.entities.length>3&&c("div",{className:"text-xs italic",style:{color:"#005C75"},children:["+",e.currentlyExecuting.entities.length-3," more entities"]})]}),n("p",{className:"text-xs mt-2",style:{color:"#005C75"},children:"This may take 2-3 minutes for environment setup"})]}),e.jobs.length>0&&c("div",{className:"space-y-2",children:[e.jobs.slice(0,5).map((a,s)=>{a.entities?.length||a.entityShas?.length,a.filePaths?.length,a.entityNames?.[0];const o=a.entities&&a.entities.length>0;return n("div",{className:"flex items-start gap-3",children:c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[c("span",{className:"text-sm font-semibold text-gray-700",children:["Job ",s+1]}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:cd(a.queuedAt)})]}),o&&c("div",{className:"space-y-1 mt-2 max-h-[120px] overflow-y-auto bg-white rounded-md p-2 border border-gray-200",children:[a.entities.slice(0,5).map(i=>c(ee,{to:`/entity/${i.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate",title:`${i.name} - ${i.filePath}`,style:{color:"#005C75"},onMouseEnter:l=>l.currentTarget.style.color="#003d52",onMouseLeave:l=>l.currentTarget.style.color="#005C75",children:[n(Oe,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[i.name,c("span",{className:"text-gray-400 ml-1",children:["(",i.filePath,")"]})]})]},i.sha)),a.entities.length>5&&c("div",{className:"text-xs text-gray-500 italic",children:["+",a.entities.length-5," more entities"]})]}),a.type==="recapture"&&a.scenarioId&&c("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:["Scenario: ",a.scenarioId]})]})},a.id)}),e.jobs.length>5&&c("div",{className:"text-xs text-gray-500 text-center py-2",children:["+",e.jobs.length-5," more jobs in queue"]})]})]})}function Se({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=k("loading"),[l,d]=k(!1),m=fe(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return G(()=>{i("loading"),d(!1);const f=m.current;f?.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:m,src:u,alt:r,onLoad:h,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Vn(e,t,r,a,s){const o=t?.scenarios?.find(Y=>Y.name===e.name),i=!!o?.startedAt,l=!!o?.screenshotStartedAt,d=!!o?.screenshotFinishedAt,m=!!o?.finishedAt,u=1800*1e3,h=l&&!d&&o?.screenshotStartedAt&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!e.metadata?.screenshotPaths?.[0]||!!e.metadata?.executionResult,f=l&&!d,g=o?.error,y=e.metadata?.executionResult?.error,v=[];if(t?.errors&&t.errors.length>0)for(const Y of t.errors)v.push({source:`${Y.phase} phase`,message:Y.message});if(t?.steps)for(const Y of t.steps)Y.error&&v.push({source:Y.name,message:Y.error});const b=!p&&!g&&!y&&v.length>0,x=!!(g||y||h||b),N=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||y?.message||(b?`Analysis error: ${v[0].message}`:null),w=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":o?.errorStack||y?.stack||null,C=(a&&s?s.jobs.some(Y=>Y.entityShas?.includes(a)||Y.type==="analysis"&&Y.entityShas&&Y.entityShas.length===0)||s.currentlyExecuting?.entityShas?.includes(a):!1)&&!i&&!x||!!o?.analyzing&&!i&&!x,S=i&&!l&&!m&&!x,A=(C||S||f)&&!x,I=(C||S)&&r===!1&&!p;let R;I?R="crashed":x?R="error":p||m?R="completed":f?R="capturing":S?R="starting":C?R="queued":R="pending";let M="📷",P="pending",F=!1,_=`Not captured: ${e.name}`;const T="border-gray-300",L=x||I?"bg-red-50":"bg-white";return x||I?(M="⚠️",P="error",_=`Error: ${I?"Analysis process crashed":N||"Unknown error"}`):C?(M="⋯",P="queued",_=`Queued: ${e.name}`):S?(M="⋯",P="starting",F=!0,_=`Starting server for ${e.name}...`):f&&!x?(M="⋯",P="capturing",F=!0,_=`Capturing ${e.name}...`):p&&(M="✓",P="completed",_=e.name),{hasError:x||I,errorMessage:I?"Analysis process crashed":N,errorStack:I?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:A,isQueued:C,isServerStarting:S,status:R,icon:M,iconType:P,shouldSpin:F,title:_,borderColor:T,bgColor:L}}function Jn({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){const o=Vn(e,void 0,void 0,t,void 0),i=e.metadata?.executionResult,l=!!i,m=(e.metadata?.data?.argumentsData||[]).length,u=i?.returnValue!==void 0&&i?.returnValue!==null,h=i?.sideEffects?.consoleOutput?.length||0,p=i?.timing?.duration||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},v=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?s?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=a?`border-2 ${v.border}`:"",x=Array.from({length:3},(w,E)=>n("div",{className:`w-1 h-1 rounded-full ${E<f?v.icon.replace("text-","bg-"):"bg-gray-300"}`},E)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
141
+ ${m} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
142
+ ${p}ms`:`Not executed: ${e.name}`;return c(ee,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${b} rounded ${v.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,children:[n("div",{className:`${v.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${v.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:x}),l&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${v.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!o.hasError&&h>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Qn({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){if(t.entityType==="library")return n(Jn,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Vn(e,r,s,t.sha,a),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${l}`,f=()=>{const y=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${y}/${d}`:y};if(u.isCaptured){const y=e.metadata?.screenshotPaths?.[0];return n(ee,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Se,{screenshotPath:y,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const y={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},x=c(te,{children:[n("style",{children:`
143
+ @keyframes strongPulse {
144
+ 0%, 100% { opacity: 0.2; }
145
+ 50% { opacity: 1; }
146
+ }
147
+ `}),c("div",{className:`${o==="small"?"text-base":o==="large"?"text-2xl":"text-xl"} font-bold tracking-widest flex items-center justify-center text-gray-600`,children:[n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"},children:"."})]})]});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return x;switch(u.iconType){case"starting":case"capturing":return x;case"error":return n(In,{...y});case"completed":return n(Tn,{...y});default:return x}};return n(ee,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:h.iconSize,children:g()})})}async function ud({request:e,context:t,params:r}){let a=t.analysisQueue;a||(a=await Ye());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return D({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedRuns:[],totalCompletedRuns:0},{status:500});const d=a.getState(),m=await Me();let u=null;if(m&&d?.currentlyExecuting?.commitSha){const{project:P,branch:F}=await Te(m),_=await Qt({projectId:P.id,branchId:F.id,shas:[d.currentlyExecuting.commitSha]});u=_&&_.length>0?_[0]:null}else u=await Xe();const h=async P=>{const F=await Le(P);if(!F)return null;const{getAnalysesForEntity:_}=await Promise.resolve().then(()=>Zo),T=await _(P,!1);return{...F,analyses:T||[]}},p=await Promise.all((d?.jobs||[]).map(async P=>{const F=[];if(P.entityShas&&P.entityShas.length>0){const _=P.entityShas.map(L=>h(L)),T=await Promise.all(_);F.push(...T.filter(L=>L!==null))}return{...P,entities:F}}));let f=null;if(d?.currentlyExecuting){const P=d.currentlyExecuting,F=[];if(P.entityShas&&P.entityShas.length>0){const _=P.entityShas.map(L=>h(L)),T=await Promise.all(_);F.push(...T.filter(L=>L!==null))}f={...P,entities:F}}const g=u?.metadata?.currentRun?.currentEntityShas||[],v=(await Promise.all(g.map(P=>h(P)))).filter(P=>P!==null),b=[];if(m)try{const{project:P,branch:F}=await Te(m),_=await Qt({projectId:P.id,branchId:F.id,limit:100});for(const T of _){const L=T.metadata?.historicalRuns||[];b.push(...L)}}catch(P){console.error("[activity.tsx] Failed to load historical runs from commits:",P)}const x=[...b].sort((P,F)=>{const _=P.archivedAt||P.createdAt||"";return(F.archivedAt||F.createdAt||"").localeCompare(_)}),N=(o-1)*i,w=N+i,E=x.slice(N,w),C=Math.ceil(x.length/i),S=await Promise.all(E.map(async P=>{const F=P.currentEntityShas||[];if(F.length===0)return{...P,entities:[]};const _=await Promise.all(F.map(T=>h(T)));return{...P,entities:_.filter(T=>T!==null)}})),A=!!f,I=p.length,R=x.filter(P=>{const F=!!P.failedAt,_=P.readyToBeCaptured,T=P.capturesCompleted??0,L=_===void 0?!0:_===0||T>=_;return!F&&!!P.analysisCompletedAt&&L}),M=await Promise.all(R.slice(0,3).map(async P=>{const F=P.currentEntityShas||[];if(F.length===0)return{...P,entities:[]};const _=await Promise.all(F.map(T=>h(T)));return{...P,entities:_.filter(T=>T!==null)}}));return D({state:{...d,jobs:p,currentlyExecuting:f},currentRun:u?.metadata?.currentRun,historicalRuns:S,totalHistoricalRuns:x.length,currentPage:o,totalPages:C,projectSlug:m,commitSha:u?.sha,queueJobs:p,currentlyExecuting:f,currentEntities:v,tab:l,hasCurrentActivity:A,queuedCount:I,recentCompletedRuns:M,totalCompletedRuns:R.length})}function md({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:s.map(o=>{const i=e===o.id;return n(ee,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
148
+ relative pb-4 px-2 text-sm font-medium transition-colors
149
+ ${i?"border-b-2":"text-gray-500 hover:text-gray-700"}
150
+ `,style:i?{color:"#005C75",borderColor:"#005C75"}:{},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`
151
+ inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full
152
+ ${i?"":"bg-gray-200 text-gray-700"}
153
+ `,style:i?{backgroundColor:"#e8f1f5",color:"#005C75"}:{},children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
154
+ inline-block w-2 h-2 rounded-full
155
+ ${i?"":"bg-gray-400"}
156
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function hd(e){const t=new Date(e),a=Math.floor((new Date().getTime()-t.getTime())/1e3);if(a<60)return"just now";const s=Math.floor(a/60);if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function pd({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedRuns:i,totalCompletedRuns:l}){const[d,m]=k({}),[u,h]=k({isKilling:!1,current:0,total:0}),p=dt(),f=!!e,g=e?.entities||[],y=!!t?.analysisCompletedAt,v=f,{lastLine:b}=Ue(a,v);return G(()=>{if(!t)return;const x=[t.analyzerPid,t.capturePid].filter(E=>!!E);if(x.length===0)return;const N=async()=>{try{const C=await(await fetch(`/api/process-status?pids=${x.join(",")}`)).json();if(C.processes){const S={};C.processes.forEach(A=>{S[A.pid]={isRunning:A.isRunning,processName:A.processName}}),m(S)}}catch(E){console.error("Failed to fetch process statuses:",E)}};N();const w=setInterval(()=>{N()},5e3);return()=>clearInterval(w)},[t?.analyzerPid,t?.capturePid]),v?c("div",{className:"bg-white rounded-xl shadow-lg p-6",style:{borderWidth:"2px",borderColor:"#005C75"},children:[c("div",{className:"flex items-start justify-between mb-4",children:[c("div",{className:"flex items-center gap-3 mb-2",children:[n("div",{className:"p-2 bg-gray-100 rounded-full animate-spin",children:n(Ka,{size:24,className:"text-gray-700"})}),n("h3",{className:"text-xl font-bold text-gray-900",children:y?"Capture in Progress":"Analysis in Progress"})]}),n("button",{onClick:o,className:"px-4 py-2 text-white rounded-md text-sm font-semibold transition-colors",style:{backgroundColor:"#005C75"},onMouseEnter:x=>x.currentTarget.style.backgroundColor="#003d52",onMouseLeave:x=>x.currentTarget.style.backgroundColor="#005C75",children:"View Logs"})]}),y&&(t?.readyToBeCaptured??0)>0&&c("div",{className:"rounded-md p-4 mb-4",style:{backgroundColor:"#f0f5f8",borderColor:"#b3d9e8",borderWidth:"1px"},children:[n("p",{className:"text-sm font-semibold mb-1",style:{color:"#00263d"},children:"Capture Progress:"}),c("div",{className:"flex items-center gap-4",children:[c("p",{className:"text-sm",style:{color:"#004560"},children:[t?.capturesCompleted??0," of"," ",t?.readyToBeCaptured??0," entities captured"]}),n("div",{className:"flex-1 rounded-full h-2",style:{backgroundColor:"#b3d9e8"},children:n("div",{className:"h-2 rounded-full transition-all duration-300",style:{backgroundColor:"#005C75",width:`${(t?.capturesCompleted??0)/(t?.readyToBeCaptured??1)*100}%`}})})]})]}),g&&g.length>0&&c("div",{className:"mb-4",children:[c("p",{className:"text-sm font-semibold text-gray-700 mb-2",children:[y?"Capturing":"Analyzing"," ",g.length," ",g.length===1?"Entity":"Entities",":"]}),n("div",{className:"space-y-3",children:g.map(x=>{const N=x.analyses?.[0],w=N?.scenarios||[],E=N?.status;return c("div",{className:"bg-gray-50 rounded-md p-3",children:[c(ee,{to:`/entity/${x.sha}`,className:"flex items-center gap-1.5 text-sm hover:underline font-medium truncate mb-2",title:`${x.name} - ${x.filePath}`,style:{color:"#005C75"},onMouseEnter:C=>C.currentTarget.style.color="#003d52",onMouseLeave:C=>C.currentTarget.style.color="#005C75",children:[n(Oe,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[x.name,c("span",{className:"text-gray-500 ml-2 text-xs",children:["(",x.filePath,")"]})]})]}),w.length>0&&n("div",{className:"flex gap-2 flex-wrap",children:w.slice(0,5).map((C,S)=>C.id?n(Qn,{scenario:C,entity:{sha:x.sha,entityType:x.entityType},analysisStatus:E,queueState:r,processIsRunning:v,size:"small"},S):null)})]},x.sha)})})]}),b&&c("div",{className:"flex flex-col gap-2 mb-4",children:[n("p",{className:"text-sm font-semibold text-gray-700",children:"Current Step:"}),n("p",{className:"text-sm text-gray-600 font-mono",children:b})]}),(t?.analyzerPid||t?.capturePid)&&c("div",{className:"flex flex-col gap-4",children:[n("p",{className:"text-sm font-semibold text-gray-700",children:"Running Processes:"}),c("div",{className:"flex items-center justify-between bg-gray-50 rounded-md p-3",children:[c("div",{className:"flex items-center gap-4 flex-wrap",children:[t.analyzerPid&&c("div",{className:"flex items-center gap-2",children:[c("span",{className:"text-xs font-mono bg-gray-200 px-2 py-1 rounded",children:["Analyzer: ",t.analyzerPid]}),d[t.analyzerPid]&&n("span",{className:`text-xs px-2 py-1 rounded ${d[t.analyzerPid].isRunning?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:d[t.analyzerPid].isRunning?"Running":"Stopped"})]}),t.capturePid&&c(te,{children:[t.analyzerPid&&n("span",{className:"text-gray-400",children:"|"}),c("div",{className:"flex items-center gap-2",children:[c("span",{className:"text-xs font-mono bg-gray-200 px-2 py-1 rounded",children:["Capture: ",t.capturePid]}),d[t.capturePid]&&n("span",{className:`text-xs px-2 py-1 rounded ${d[t.capturePid].isRunning?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:d[t.capturePid].isRunning?"Running":"Stopped"})]})]})]}),(d[t.analyzerPid]?.isRunning||d[t.capturePid]?.isRunning)&&c("div",{className:"flex items-center gap-3",children:[u.isKilling&&c("span",{className:"text-xs text-gray-600 font-medium",children:["Killing process ",u.current," of"," ",u.total,"..."]}),n("button",{onClick:()=>{const x=[t.analyzerPid,t.capturePid].filter(E=>!!E&&d[E]?.isRunning);if(x.length===0)return;const N=x.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${N})?`))return;h({isKilling:!0,current:1,total:x.length}),(async()=>{for(let E=0;E<x.length;E++){const C=x[E];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:C,commitSha:s||""})})}catch(S){console.error(`Failed to kill process ${C}:`,S)}E<x.length-1&&h({isKilling:!0,current:E+2,total:x.length})}h({isKilling:!1,current:0,total:0}),p.revalidate()})()},disabled:u.isKilling,className:"px-3 py-1 bg-red-600 text-white rounded-md text-xs font-semibold hover:bg-red-700 transition-colors whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed",children:u.isKilling?"Killing...":"Kill All Processes"})]})]})]})]}):c("div",{className:"space-y-6",children:[c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-2 bg-gray-200 rounded-lg",children:n(Dr,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Current Activity"}),c("p",{className:"text-gray-500",children:["There are no analyses currently running. Trigger an analysis from the"," ",n(ee,{to:"/git",className:"text-[#005C75] underline hover:text-[#004a5e]",children:"Git"})," ","or"," ",n(ee,{to:"/files",className:"text-[#005C75] underline hover:text-[#004a5e]",children:"Files"})," ","page."]})]}),i&&i.length>0&&c("div",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Recent Completed Analyses"}),n("div",{className:"space-y-3",children:i.map(x=>{const N=x.analysisCompletedAt||x.archivedAt||x.createdAt,w=x.entities&&x.entities.length>0;return c("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n(Tn,{size:18,className:"text-green-600"}),n("span",{className:"text-sm font-semibold text-gray-900",children:"Completed"}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:N?hd(N):"Unknown"})]}),w&&c("div",{className:"ml-7 space-y-1",children:[x.entities.slice(0,3).map(E=>c(ee,{to:`/entity/${E.sha}`,className:"flex items-center gap-1.5 text-sm hover:underline truncate",title:`${E.name} - ${E.filePath}`,style:{color:"#005C75"},onMouseEnter:C=>C.currentTarget.style.color="#003d52",onMouseLeave:C=>C.currentTarget.style.color="#005C75",children:[n(Oe,{size:14,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[E.name,c("span",{className:"text-gray-400 ml-1 text-xs",children:["(",E.filePath,")"]})]})]},E.sha)),x.entities.length>3&&c("div",{className:"text-xs text-gray-500 italic",children:["+",x.entities.length-3," more entities"]})]})]},x.id)})}),l>3&&n("div",{className:"mt-4 text-center",children:n(ee,{to:"/activity/historic",className:"text-sm font-medium",style:{color:"#005C75"},onMouseEnter:x=>x.currentTarget.style.color="#003d52",onMouseLeave:x=>x.currentTarget.style.color="#005C75",children:"View All Historic Activity →"})})]})]})}function fd({queueJobs:e,state:t,currentRun:r}){return!e||e.length===0?c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-3 bg-gray-200 rounded-lg",children:n(Va,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Queued Jobs"}),n("p",{className:"text-gray-500",children:"Analysis jobs will appear here when they are queued but not yet started."})]}):n("div",{children:n(dd,{state:t,currentRun:r})})}function gd({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s}){return t===0?c("div",{className:"bg-gray-50 rounded-xl p-12 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-3 bg-gray-200 rounded-lg",children:n(Lr,{size:20,className:"text-gray-600"})})}),n("h3",{className:"text-xl font-semibold text-gray-700 mb-2",children:"No Historic Activity"}),n("p",{className:"text-gray-500",children:"Completed analyses will appear here for historical reference."})]}):c("div",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"space-y-3",children:e.map(o=>{const i=!!o.failedAt,l=o.readyToBeCaptured,d=o.capturesCompleted??0,m=l===void 0?!0:l===0||d>=l,u=!i&&!!o.analysisCompletedAt&&m,h=o.createdAt?new Date(o.createdAt):null,p=o.failedAt?new Date(o.failedAt):o.analysisCompletedAt?new Date(o.analysisCompletedAt):null,f=h&&p?(p.getTime()-h.getTime())/1e3:null,g=o.entities&&o.entities.length>0;return n("div",{className:`border rounded-lg p-4 ${i?"bg-red-50 border-red-200":u?"bg-green-50 border-green-200":"bg-gray-50 border-gray-200"}`,children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[i?n(In,{size:20,className:"text-red-500"}):u?n(Tn,{size:20,className:"text-green-500"}):n(Dr,{size:20,className:"text-gray-400"}),n("span",{className:"text-sm font-semibold text-gray-900",children:i?"Failed":u?"Completed":"Incomplete"}),n("span",{className:"text-xs text-gray-400",children:"•"}),n("span",{className:"text-xs text-gray-500",children:o.archivedAt?new Date(o.archivedAt).toLocaleString():o.createdAt?new Date(o.createdAt).toLocaleString():"Unknown"})]}),g&&c("div",{className:"ml-7 mt-2 space-y-2 max-h-[300px] overflow-y-auto bg-white rounded-md p-2 border border-gray-200",children:[o.entities.slice(0,5).map(y=>{const v=y.analyses?.[0],b=v?.scenarios||[];return c("div",{className:"pb-2 border-b last:border-b-0 border-gray-100",children:[c(ee,{to:`/entity/${y.sha}`,className:"flex items-center gap-1.5 text-xs hover:underline font-medium truncate mb-1",title:`${y.name} - ${y.filePath}`,style:{color:"#005C75"},onMouseEnter:x=>x.currentTarget.style.color="#003d52",onMouseLeave:x=>x.currentTarget.style.color="#005C75",children:[n(Oe,{size:12,style:{strokeWidth:1.5,flexShrink:0}}),c("span",{className:"truncate",children:[y.name,c("span",{className:"text-gray-400 ml-1",children:["(",y.filePath,")"]})]})]}),b.length>0&&n("div",{className:"flex gap-1.5 flex-wrap mt-1.5",children:b.slice(0,5).map((x,N)=>x.id?n(Qn,{scenario:x,entity:{sha:y.sha,entityType:y.entityType},analysisStatus:v?.status,queueState:void 0,processIsRunning:!1,size:"small"},N):null)})]},y.sha)}),o.entities.length>5&&c("div",{className:"text-xs text-gray-500 italic pt-1",children:["+",o.entities.length-5," more entities"]})]}),o.failureReason&&n("p",{className:"text-xs text-red-600 mt-2 font-mono ml-7",children:o.failureReason})]}),f!==null&&c("div",{className:"text-xs text-gray-500",children:[f.toFixed(1),"s"]})]})},o.id)})}),a>1&&c("div",{className:"mt-6 flex items-center justify-between border-t border-gray-200 pt-4",children:[c("div",{className:"text-sm text-gray-600",children:["Showing ",(r-1)*20+1," -"," ",Math.min(r*20,t)," of"," ",t," runs"]}),c("div",{className:"flex gap-2",children:[r>1&&n(ee,{to:`/activity/${s}?page=${r-1}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors",children:"Previous"}),r<a&&n(ee,{to:`/activity/${s}?page=${r+1}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors",children:"Next"})]})]})]})}const yd=Ie(function(){const t=De(),r=Rr(),[a,s]=k(!1),o=r.tab||"current";return c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-gray-600",children:"View queued, current, and historical analysis activity"})]}),n(md,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(pd,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedRuns:t.recentCompletedRuns,totalCompletedRuns:t.totalCompletedRuns}),o==="queued"&&n(fd,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(gd,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o}),a&&t.projectSlug&&n(ut,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]})}),xd=Object.freeze(Object.defineProperty({__proto__:null,default:yd,loader:ud},Symbol.toStringTag,{value:"Module"}));async function Aa(e,t,r){await Ae();const a=await qe({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=ie();if(!s)throw new Error("Project root not found");const o=K.join(s,".codeyam","config.json"),i=JSON.parse(W.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=`/tmp/codeyam/local-dev/${l}/codeyam/log.txt`;try{W.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Te(l),u=m.metadata?.packageManager||"npm",h=m.metadata?.webapps?.[0]?.framework??_t.Next,p=3112,f=`/tmp/codeyam/local-dev/${l}/project`,g=m.metadata?.webapps||[];if(g.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=g.length>1?g.find(E=>a.filePath.includes(E.path??""))??g[0]:g[0];await Pt(e,E=>{if(E&&(E.readyToBeCaptured=!0,E.scenarios))for(const C of E.scenarios)(!t||C.name===t)&&(delete C.screenshotStartedAt,delete C.screenshotFinishedAt,delete C.interactiveStartedAt,delete C.interactiveFinishedAt,delete C.error,delete C.errorStack)});const{jobId:v}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),x=(()=>{const E=y?.startCommand;if(!E)return`${u} ${u==="npm"?"run ":""}dev`;const C=E.args?.map(R=>R.replace(/\$PORT/g,String(p)))??[],S=[],A=i.environmentVariables||[];for(const R of A)if(R.key&&R.value!==void 0){const M=String(R.value).replace(/'/g,"'\\''");S.push(`${R.key}='${M}'`)}if(E.env)for(const[R,M]of Object.entries(E.env)){const F=String(M).replace(/\$PORT/g,String(p)).replace(/'/g,"'\\''");S.push(`${R}='${F}'`)}const I=S.length>0?S.join(" ")+" ":"";return E.command==="sh"&&C[0]==="-c"&&C[1]?`${I}sh -c "${C[1]}"`:`${I}${E.command} ${C.join(" ")}`})(),N={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:f}]},{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 ${f}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:v,analysisId:e,scenarioId:t,projectPath:f,projectSlug:l,port:p,packageManager:u,framework:h,instructions:N}}async function bd({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),s=r.searchParams.get("scenarioId")||void 0;if(!a)return D({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await Ye()),!o)return D({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Aa(a,s,o);return D({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),D({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function vd({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ye()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return D({error:"Missing required field: analysisId"},{status:400});const i=await Aa(s,o,r);return D({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),D({error:"Failed to setup debug environment",details:s},{status:500})}}const wd=Object.freeze(Object.defineProperty({__proto__:null,action:vd,loader:bd},Symbol.toStringTag,{value:"Module"}));async function Cd({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ye()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return D({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return D({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const l=await Vl(s,i,r);return console.log("[API] Recapture queued",l),D({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),D({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Nd=Object.freeze(Object.defineProperty({__proto__:null,action:Cd},Symbol.toStringTag,{value:"Module"}));function Ea(e,t){const r=e.metadata?.isUncommitted===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(i=>i.scenarios&&i.scenarios.length>0);if(!r){const i=!!e.metadata?.previousVersionWithAnalyses,l=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return i||l?a?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:a?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const s=!!e.metadata?.previousCommittedSha;if(!!e.metadata?.previousVersionWithAnalyses||s){const i=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===e.metadata?.previousVersionWithAnalyses;return a&&!i?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:a?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return a?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function Zn(e){return Ea(e).hasOutdatedSimulations}const zt=70;function Sd({scenarios:e,analysis:t,selectedScenario:r,entitySha:a,cacheBuster:s,activeTab:o,entityType:i,entity:l,queueState:d,processIsRunning:m,viewMode:u,setViewMode:h,onDebugSetup:p,debugFetcher:f}){const g=fe(null),[y,v]=k(new Set);G(()=>{g.current&&o==="scenarios"&&g.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[r?.id,o]);const b=w=>`/entity/${a}/scenarios/${w}`,x=w=>{v(E=>{const C=new Set(E);return C.has(w)?C.delete(w):C.add(w),C})},N=(w,E=2)=>{const S=w.split(`
157
+ `).slice(0,E).join(" ").trim();return S.length>zt?S.substring(0,zt-3):(w.split(`
158
+ `).length>E||w.length>S.length,S)};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3",children:[h&&c("div",{children:[n("div",{className:"text-[10px] text-[#626262] font-medium mb-[6px]",children:"View"}),c("div",{className:"grid grid-cols-2 gap-0",role:"group","aria-label":"View mode selector",children:[n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-l-[4px] border border-[#c7c7c7] transition-colors ${u==="screenshot"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("screenshot"),"aria-label":"Screenshot view","aria-pressed":u==="screenshot",children:"📸 Screenshot"}),n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-r-[4px] border border-[#c7c7c7] border-l-0 transition-colors ${u==="interactive"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("interactive"),"aria-label":"Interactive view","aria-pressed":u==="interactive",children:"🎮 Interactive"})]})]}),r&&c("div",{className:"grid grid-cols-2 gap-1",children:[n(ee,{to:`/entity/${a}/edit/${r.id}`,className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] no-underline flex items-center justify-center",title:"Edit Scenario Data",children:"Edit Scenario"}),n("button",{className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:bg-gray-400 disabled:text-gray-600 disabled:cursor-not-allowed flex items-center justify-center",onClick:p,disabled:f?.state!=="idle",title:"Setup Debug Environment",children:f?.state==="idle"?"Debug Scenario":"Setting up..."})]}),l&&l.filePath&&n("div",{children:n(ee,{to:`/entity/${a}/create-scenario`,className:"w-full px-[10px] 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] no-underline flex items-center justify-center",children:"Create New Scenario"})}),n("div",{className:"border-t border-[#e1e1e1] pt-3",children:n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Scenarios"})}),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((w,E)=>{const C=r?.id===w.id,S=y.has(w.id||"");return w.id?c(ee,{to:b(w.id),ref:C?g:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${C?"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(Qn,{scenario:w,entity:{sha:a,entityType:i},analysisStatus:t?.status,queueState:d,processIsRunning:m,size:"large",cacheBuster:s,viewMode:u})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:w.name}),w.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?w.description:N(w.description),!S&&w.description.length>zt&&c(te,{children:["...",n("button",{onClick:A=>{A.preventDefault(),A.stopPropagation(),x(w.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&w.description.length>zt&&n("button",{onClick:A=>{A.preventDefault(),A.stopPropagation(),x(w.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},E):null})})})]})}function Ad({scenario:e,analysis:t,entity:r}){const a=e.metadata?.executionResult||null,s=e.metadata?.data?.argumentsData||[],o=i=>{if(!i)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const l=[],d=i.sideEffects?.consoleOutput||[];d.length>0&&(l.push(`Console Output: ${d.length} log ${d.length===1?"entry":"entries"} captured`),d.forEach(h=>{l.push(` [${h.level.toUpperCase()}] ${h.args.join(" ")}`)}));const m=i.sideEffects?.fileWrites||[];m.length>0&&(l.push(`
159
+ File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(h=>{l.push(` ${h.operation}: ${h.path}${h.size?` (${h.size} bytes)`:""}`)}));const u=i.sideEffects?.apiCalls||[];return u.length>0&&(l.push(`
160
+ API Calls: ${u.length} ${u.length===1?"call":"calls"} made`),u.forEach(h=>{l.push(` ${h.method} ${h.url}${h.status?` → ${h.status}`:""}${h.duration?` (${h.duration}ms)`:""}`)})),i.error&&l.push(`
161
+ Error: ${i.error.name||"Error"}: ${i.error.message}`),l.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":l.join(`
162
+ `)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const Bt=10,Ed=1024;function _d({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a}){const[s,o]=k(null),i=fe(null),l=ne(()=>[...a].sort((y,v)=>y.width-v.width),[a]),{fittingPresets:d,overflowPresets:m}=ne(()=>{const y=[],v=[];for(const b of l)b.width<=Ed?y.push(b):v.push(b);return v.sort((b,x)=>x.width-b.width),{fittingPresets:y,overflowPresets:v}},[l]),u=Z(y=>{if(!i.current)return null;const v=i.current.getBoundingClientRect(),b=y-v.left,x=v.width,N=x/2,E=(d.length>0?d[d.length-1].width:0)/2,C=N-E,S=N+E,A=m.length>0?(m.length-1)*Bt:0;if(m.length>0){if(b<C){if(b<=A){const R=Math.min(Math.floor(b/Bt),m.length-1);return m[R]}return m[m.length-1]}if(b>S){const R=x-b;if(R<=A){const M=Math.min(Math.floor(R/Bt),m.length-1);return m[M]}return m[m.length-1]}}const I=Math.abs(b-N);for(let R=d.length-1;R>=0;R--){const M=d[R],P=d[R-1],F=M.width/2,_=P?P.width/2:0;if(I<=F&&I>=_)return M}return d[0]||m[m.length-1]||null},[d,m]),h=Z(y=>{const v=u(y.clientX);o(v)},[u]),p=Z(()=>{o(null)},[]),f=Z(y=>{const v=u(y.clientX);v&&r(v)},[u,r]),g=s||{name:t,width:e};return c("div",{ref:i,className:"relative h-6 bg-[#f6f9fc] shrink-0 overflow-hidden cursor-pointer",onMouseMove:h,onMouseLeave:p,onClick:f,children:[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-[rgba(0,92,117,0.15)]",style:{width:`${e}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:d.map(y=>{const v=y.width===e,b=s?.name===y.name,x=y.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${x}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||b?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${x}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||b?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((y,v)=>{const b=v*Bt,x=y.width===e,N=s?.name===y.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${b}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${x||N?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${b}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${x||N?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${s?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[g.name," - ",g.width,"px"]})})]})}function Pd({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=k(""),[i,l]=k(""),d=()=>{const u=s.trim();if(!u){l("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&s.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors",children:"Cancel"}),n("button",{onClick:d,disabled:!s.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function Md(e){const[t,r]=k([]),a=e?`codeyam-custom-sizes-${e}`:null;G(()=>{if(!a||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(a);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[a]);const s=Z(l=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=Z((l,d,m)=>{r(u=>{const h=u.findIndex(g=>g.name===l),p={name:l,width:d,height:m};let f;return h>=0?(f=[...u],f[h]=p):f=[...u,p],s(f),f})},[s]),i=Z(l=>{r(d=>{const m=d.filter(u=>u.name!==l);return s(m),m})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function rn({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o}){const[i,l]=k(!1),d=Z(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),s)}).catch(m=>{console.error("Failed to copy:",m)})},[e,s]);return n("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":o||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?r:t})}function Ut({scenarioId:e,analysisId:t}){const[r,a]=k(!1),[s,o]=k(!1),[i,l]=k(null),d=e||t;if(!d)return null;const m=`/debug ${d}`,u=async()=>{o(!0);try{const{default:p}=await import("html2canvas-pro"),g=(await p(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(g),a(!0)}catch(p){console.error("Screenshot capture failed:",p),a(!0)}finally{o(!1)}};return c(te,{children:[n("div",{className:"mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-blue-600 text-xl shrink-0",children:"🤖"}),c("div",{className:"flex-1",children:[n("h4",{className:"text-sm font-semibold text-blue-800 m-0 mb-2",children:"Claude can help debug this error"}),n("p",{className:"text-sm text-blue-700 m-0 mb-3",children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center gap-2 bg-white border border-blue-200 rounded p-3 mb-4",children:[n("code",{className:"text-sm text-blue-900 font-mono flex-1 wrap-break-word",children:m}),n(rn,{content:m,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1 bg-blue-600 text-white text-xs font-medium rounded hover:bg-blue-700 transition-colors shrink-0"})]}),c("div",{className:"pt-3 border-t border-blue-200",children:[n("p",{className:"text-xs text-blue-700 m-0 mb-2",children:"If Claude is unable to address this issue or suggests reporting it, please do so."}),n("button",{onClick:()=>{u()},disabled:s,className:"cursor-pointer px-3 py-1.5 bg-white border border-blue-300 text-blue-700 text-xs font-medium rounded hover:bg-blue-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:s?"Capturing...":"Report Issue"})]})]})]})}),n(On,{isOpen:r,onClose:()=>{a(!1),l(null)},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 Nr=1440,qt=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function _a({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0}){const m=ue(),[u,h]=k(!1),[p,f]=k(!1),[g,y]=k({name:"Desktop",width:Nr,height:900}),[v,b]=k(Nr),[x,N]=k(1),{customSizes:w,addCustomSize:E,removeCustomSize:C}=Md(l),S=ne(()=>[...qt,...w],[w]),A=(X,re)=>{b(X);const me=S.find(he=>he.width===X&&he.height===re);y({name:me?.name||"Custom",width:X,height:re})},I=X=>{b(X.width),y({name:X.name,width:X.width,height:X.height})},R=X=>{E(X,g.width,g.height??900),f(!1),y(re=>({...re,name:X}))},M=(X,re)=>{b(X);const me=S.find(he=>he.width===X&&he.height===re);y(he=>({name:me?.name||"Custom",width:X,height:he.height}))},P=e?.metadata?.screenshotPaths?.[0],F=ne(()=>!e||!t?.status?.scenarios?null:t.status.scenarios.find(X=>X.name===e.name),[e,t?.status?.scenarios]),_=ne(()=>{const X=[];if(t?.status?.errors&&t.status.errors.length>0)for(const re of t.status.errors)X.push({source:`${re.phase} phase`,message:re.message,stack:re.stack});if(t?.status?.steps)for(const re of t.status.steps)re.error&&X.push({source:re.name,message:re.error,stack:re.errorStack});return X},[t?.status?.errors,t?.status?.steps]),T=F?.error||(e?.metadata?.error?"Error during capture":null),L=F?.errorStack,{interactiveServerUrl:Y,isStarting:J,isLoading:O,showIframe:B,iframeKey:H,onIframeLoad:j}=Wn({analysisId:t?.id,scenarioId:e?.id,scenarioName:e?.name,projectSlug:l,enabled:a==="interactive"}),U=ne(()=>Y||null,[Y]),$=!i&&o&&e&&!e.metadata?.screenshotPaths?.[0]&&t?.status?.scenarios?.some(X=>X.name===e.name&&X.screenshotStartedAt&&!X.screenshotFinishedAt),{lastLine:q}=Ue(l,i||a==="interactive"||$||!1);return e?c(te,{children:[n("main",{className:"flex-1 bg-[#f9f9f9] overflow-auto flex flex-col min-w-0",children:(i||$)&&!P&&!T&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:$?`Capturing ${r?.name}`:`Analyzing ${r?.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:$?`Taking screenshots for ${t?.scenarios?.length||0} scenario${t?.scenarios?.length!==1?"s":""}...`:`Generating simulations and scenarios for this ${r?.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),q&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:q,children:q})]})]})}),l&&n("button",{onClick:()=>h(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&(P||T)||a==="interactive"&&(U||J)||a==="data"?c(te,{children:[T&&!P&&n("div",{className:"bg-red-50 border-l-4 border-red-500 mx-5 mt-4 p-4 rounded-r overflow-auto",role:"alert",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-red-500 text-xl shrink-0","aria-hidden":"true",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-sm font-semibold text-red-800 m-0 mb-2",children:"Capture Error"}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-700 m-0 mb-2 font-mono whitespace-pre-wrap wrap-break-word",children:T})}),L&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-600 cursor-pointer hover:text-red-800 font-medium",children:"View stack trace"}),n("div",{className:"mt-2 p-3 bg-red-100 rounded max-h-[300px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:L})})]}),n(Ut,{scenarioId:e?.id,analysisId:t?.id})]})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[U&&n("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center",children:n(hi,{presets:[...qt],customSizes:w,currentWidth:g.width,currentHeight:g.height??900,scale:x,onSizeChange:A,onSaveCustomSize:()=>f(!0),onRemoveCustomSize:C})}),U&&n("div",{className:"bg-[#f6f9fc] border-b border-[rgba(0,92,117,0.25)] flex justify-center",children:n("div",{style:{maxWidth:`${qt[qt.length-1].width}px`,width:"100%"},children:n(_d,{currentViewportWidth:v,currentPresetName:g.name,onDevicePresetClick:I,devicePresets:S})})}),n(Gn,{scenarioId:e.id,scenarioName:e.name,iframeUrl:U,isStarting:J,isLoading:O,showIframe:B,iframeKey:H,onIframeLoad:j,onScaleChange:N,onDimensionChange:M,projectSlug:l,defaultWidth:g.width,defaultHeight:g.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(Ad,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${v}px`},children:(P||!T)&&n(Se,{screenshotPath:P,cacheBuster:s,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!P?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),q&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:q})]}),l&&n("button",{onClick:()=>h(!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"})]})]})})}):T?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),c("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),c("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(ee,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),c("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:T})})]}),L&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:L})})]}),n(Ut,{scenarioId:e?.id,analysisId:t?.id})]})]})})]}):_.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Error"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:_.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${_.length} errors occurred during analysis. Screenshot capture was not completed.`}),_.map((X,re)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:X.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:X.message})}),X.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:X.stack})})]})]},re)),n(Ut,{scenarioId:e?.id,analysisId:t?.id})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),u&&l&&n(ut,{projectSlug:l,onClose:()=>h(!1)}),p&&n(Pd,{width:g.width,height:g.height??900,onSave:R,onCancel:()=>f(!1)})]}):!o&&r?i?n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:$?"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."}),q&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:q}),l&&n("button",{onClick:()=>h(!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"})]})}):_.length>0?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 bg-[#f6f9fc] overflow-auto",children:c("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl",children:[c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:_.length===1?"An error occurred during analysis. No scenarios were generated.":`${_.length} errors occurred during analysis. No scenarios were generated.`}),_.map((X,re)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:X.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:X.message})}),X.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:X.stack})})]})]},re))]})]}),r.filePath&&n("div",{className:"flex justify-center mt-4",children:n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[42px] px-6 py-2 bg-[#005c75] text-white border-none rounded-lg text-sm font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Retrying...":"Retry Analysis"})}),n(Ut,{analysisId:t?.id})]})}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})}):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"})})}function Sr({hasIndirectBadge:e,onAnalyze:t}){return c(te,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),c("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function kd({entity:e,history:t}){const[r,a]=k("entity"),[s,o]=k(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ne(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(p=>{p.scenarios?.forEach(f=>{u.has(f.name)||u.set(f.name,[]),u.get(f.name).push({version:h,analysis:p,scenario:f})})})}),Array.from(u.entries()).map(([h,p])=>({name:h,description:p[0]?.scenario.description||"",versions:p.sort((f,g)=>{const y=new Date(f.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-y})}))},[t]),d=l.length,m=u=>{o(h=>{const p=new Set(h);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>a("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),c("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?c("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[u.sha===e?.sha&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c("span",{className:"text-xs font-mono text-[#646464] leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>n("div",{children:!p.scenarios||p.scenarios.length===0?n(Sr,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):c(te,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[p.scenarios.length," scenario",p.scenarios.length!==1?"s":""]})]})}),p.metadata?.scenarioChangesOverview&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),p.scenarios&&p.scenarios.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:p.scenarios.map((g,y)=>{const v=g.metadata?.screenshotPaths?.[0],b=`${g.name}-${y}`;return c("div",{className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:v?n(Se,{screenshotPath:v,alt:g.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:g.name})})]},b)})})})]})},p.id||f))}):n(Sr,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,h)=>{const p=s.has(u.name),f=p?u.versions:u.versions.slice(0,1),g=u.versions.length-1;return u.versions[0]?.version.sha,e?.sha,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((v,b)=>{const{version:x,analysis:N,scenario:w}=v,E=w.metadata?.screenshotPaths?.[0],C=b===0;return c("div",{className:`flex gap-5 items-start ${C?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n("div",{className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0",children:E?n(Se,{screenshotPath:E,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[x.sha===e?.sha&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),C&&u.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),c("p",{className:"text-xs font-mono text-[#646464] m-0 leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:x.sha.substring(0,8)})]}),N.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${x.sha}-${b}`)}),g>0&&c("button",{onClick:()=>m(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Be({type:e}){const t={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"}},r=t[e]||t.other,a=()=>{switch(e){case"library":return n(Or,{size:14,color:r.iconColor});case"visual":return n(nt,{size:14,color:r.iconColor});case"type":return n(Za,{size:14,color:r.iconColor});case"data":return n(Lr,{size:14,color:r.iconColor});case"index":return n(Qa,{size:14,color:r.iconColor});case"functionCall":return n(nr,{size:14,color:r.iconColor});case"class":return n(Ja,{size:14,color:r.iconColor});case"method":return n(nr,{size:14,color:r.iconColor});case"other":return n(Oe,{size:14,color:r.iconColor});default:return n(Oe,{size:14,color:r.iconColor})}};return n("span",{className:`flex items-center justify-center w-5 h-5 rounded ${r.bgColor}`,children:a()})}function Ar({entity:e,analysisInfo:t,from:r}){return n(ee,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Se,{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(Be,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Be,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?c(te,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(te,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]})})]})]})},e.sha)}const Er=e=>{const t=e.analysisStatus?.status||"not_analyzed",r=e.analysisStatus?.scenarioCount||0,a=e.analysisStatus?.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function Td({importedEntities:e,importingEntities:t}){const[r]=Mn(),a=r.get("from"),s=e.length>0,o=t.length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),s?n("div",{className:"p-6 space-y-4",children:e.map(i=>n(Ar,{entity:i,analysisInfo:Er(i),from:a},i.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),o?n("div",{className:"p-6 space-y-4",children:t.map(i=>n(Ar,{entity:i,analysisInfo:Er(i),from:a},i.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 Id({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Td,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Rd({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(St,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function St({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,l]=k(r||t<2);if(G(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(te,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>n("div",{className:"py-0.5",children:n(St,{data:m,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=p=>Array.isArray(p)&&p.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[m.length,"}"]})]}),i?c(te,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(p=>{const f=e[p],g=u(f),y=h(f);return n("div",{className:"py-0.5",children:g?n(Xn,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(er,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(te,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(St,{data:f,depth:t+1,defaultExpanded:r,maxDepth:a})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Xn({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=k(a||r<2),l=Object.keys(t);return G(()=>{i(a||r<2)},[a,r]),c(te,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(te,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const m=t[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(Xn,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):h?n(er,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):c(te,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(St,{data:m,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function er({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=k(a||r<2);return G(()=>{i(a||r<2)},[a,r]),c(te,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(te,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const m=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:m?n(Xn,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(er,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):n(St,{data:l,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function wn({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function _r({label:e,isActive:t,onClick:r,disabled:a=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Pr({call:e,scenarioName:t}){const[r,a]=k(!1),[s,o]=k("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const g=[];return p&&g.push(`${p.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},m=ne(()=>{try{const p=JSON.parse(e.response);return p.choices?.[0]?.message?.content?p.choices[0].message.content:p.content?.[0]?.text?p.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]),h=ne(()=>{if(t)return t;try{return JSON.parse(e.props)?.scenario?.name||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),s==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),s==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),s==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Mr=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function jd({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){const[o,i]=k("entity"),[l,d]=k("isolatedDataStructure"),[m,u]=k(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=k("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ne(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const N=[...s.entityCalls,...s.analysisCalls],w=N.filter(C=>C.object_type==="entity"||Mr.includes(C.prompt_type)),E=N.filter(C=>C.object_type!=="entity"&&!Mr.includes(C.prompt_type));return w.sort((C,S)=>S.created_at-C.created_at),E.sort((C,S)=>S.created_at-C.created_at),{entityLlmCalls:w,scenarioLlmCalls:E,totalLlmCalls:N.length}},[s]),v=[{id:"isolatedDataStructure",title:"Isolated Data Structure",data:e?.metadata?.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:t?.metadata?.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:e?.metadata?.isolatedDataStructure?.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"keyAttributes",title:"Key Attributes",data:t?.metadata?.keyAttributes,description:"Important attributes identified during analysis"},{id:"importedExports",title:"Imported Dependencies",data:e?.metadata?.importedExports,description:"The imported dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:t?.metadata?.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=v.filter(N=>N.data!==void 0&&N.data!==null).length;let x=null;if(o==="entity"){const N=v.find(w=>w.id===l);N&&N.data!==void 0&&N.data!==null&&(x={title:N.title,description:N.description,data:N.data})}else if(o==="scenarios"&&m){const N=r.find(w=>(w.id||w.name)===m.scenarioId);N&&(x={title:N.name,description:N.description||"Scenario data and configuration",data:N.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(wn,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(wn,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(wn,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),t?.metadata?.analyzerVersion&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(N=>n(Pr,{call:N},N.id)):g.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):g.map(N=>n(Pr,{call:N},N.id))})]}):c("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?c(te,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:v.map(N=>{const w=N.data!==void 0&&N.data!==null;return n(_r,{label:N.title,isActive:l===N.id,onClick:()=>d(N.id),disabled:!w},N.id)})})]}):c(te,{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(N=>{const w=N.id||N.name,E=m?.scenarioId===w;return n(_r,{label:N.name,isActive:E,onClick:()=>u({scenarioId:w})},w)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:x?n($d,{title:x.title,description:x.description,data:x.data}):o==="scenarios"&&r.length===0?n(kr,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(kr,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function kr({title:e,description:t,onAnalyze:r}){return c("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function $d({title:e,description:t,data:r}){const[a,s]=k(!0),[o,i]=k("Copy JSON");return c(te,{children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>s(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>s(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:o})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(Rd,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Dd({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=ue();return G(()=>{if(e?.sha&&s.state==="idle"&&!s.data){const o=t?.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e?.sha,t?.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(jd,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}const Ld={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Od={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Fd=2e3,Yd=e=>{if(!e)return"typescript";switch(e.split(".").pop()?.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 zd({entity:e,entityCode:t}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e?.filePath})]}),t&&n(rn,{content:t,label:"Copy Code",duration:Fd,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(Ms,{language:Yd(e?.filePath),style:ks,showLineNumbers:!0,customStyle:Ld,lineNumberStyle:Od,children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Bd=({data:e})=>[{title:e?.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Ud({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:s,defaultShouldRevalidate:o}){return r.pathname===a.pathname&&r.search===a.search?o:!!(e.sha!==t.sha||s)}async function qd({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",m=l[1]||null,u=l[2]||null,h=r.analysisQueue,p=h?h.getState():{paused:!1,jobs:[]},[f,g,y,v,b]=await Promise.all([Le(a),cn(a,!1),Me(),Xe(),ei(ie()||process.cwd())]),x=g&&g.length>0?g[0]:null;let N={importedEntities:[],importingEntities:[]},w=null,E=[];return f&&(N=await na(f),w=await aa(f),E=await sa(f)),D({entity:f??void 0,analysis:x??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:w??void 0,history:E,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:v,hasAnApiKey:b,queueState:p})}const Wd=Ie(function(){const t=De(),s=(Rr()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,l=s[2]||null,d=t.entity,m=t.analysis,u=t.projectSlug;t.from;const h=t.relatedEntities,p=t.entityCode,f=t.history,g=t.currentCommit,y=t.hasAnApiKey,v=t.queueState,b=m?.scenarios||[],x=ct(),N=fe(null);G(()=>{N.current===null&&(N.current=window.history.length)},[]);const w=()=>{if(typeof window>"u")return;const Q=window.history.state;if(Q===null||Q?.idx===void 0||Q?.idx===0)x("/");else{const be=window.history.length,de=N.current;if(de!==null&&be>de){const je=be-de+1;x(-je)}else x(-1)}},E=!!v.currentlyExecuting,C=o,S=ne(()=>{if(C!=="scenarios")return null;if(i){const Q=b.find(be=>be.id===i);if(Q)return Q}return b.length>0?b[0]:null},[C,i,b]),[A,I]=k(()=>l||(d?.entityType==="library"?"data":"screenshot"));G(()=>{l&&l!==A&&I(l)},[l]);const[R,M]=k(!1),[P,F]=k(""),[_,T]=k(!1),[L,Y]=k(Date.now()),[J,O]=k(null),[B,H]=k(!1),[j,U]=k(!1),[$,q]=k(!1),[se,Ee]=k(!1),[X,re]=k(null),me=ue(),he=ue();G(()=>{he.state==="idle"&&!he.data&&he.load("/api/generate-report")},[he]);const kt=he.data?.defaultEmail||"",xe=ue(),Re=ue(),we=ue(),ye=dt(),ft=g?.metadata?.currentRun,gt=!!ft?.createdAt&&!ft?.analysisCompletedAt,Tt=v.jobs.some(Q=>Q.entityShas?.includes(d?.sha||"")||Q.type==="analysis"&&Q.commitSha===g?.sha&&Q.entityShas&&Q.entityShas.length===0),It=ft?.currentEntityShas?.includes(d?.sha||"")??!1,Rt=It;d?.metadata?.defaultWidth||m?.metadata?.defaultWidth,me.state==="submitting"||me.state,ne(()=>!!S?.metadata?.interactiveExamplePath,[S]);const{isCompleted:We}=Ue(u,_);G(()=>{me.state==="idle"&&me.data&&(me.data.success?setTimeout(()=>{Y(Date.now()),ye.revalidate(),T(!1)},1500):me.data.error&&(T(!1),alert(`Recapture failed: ${me.data.error}`)))},[me.state,me.data,ye]),G(()=>{_&&We&&setTimeout(()=>{Y(Date.now()),ye.revalidate(),T(!1)},1500)},[_,We,ye]),G(()=>{if(xe.state==="idle"&&xe.data)if(xe.data.success){O(xe.data),H(!0);const Q=xe.data.jobId;if(Q){const be=async()=>{try{const je=await fetch("/api/queue?queryType=job&jobId="+encodeURIComponent(Q));if(!je.ok){const xt=await je.text();console.error("[Debug Setup] Poll failed with status",je.status,":",xt);return}(await je.json()).status==="completed"&&(clearInterval(de),O(xt=>xt?{...xt,complete:!0,instructions:{title:"Debug Environment Ready ✓",sections:xt.instructions?.sections?.map(et=>et.heading==="Status"?{heading:"Status",items:[{content:"Setup complete! Your debug environment is ready."},...et.items.slice(1)]}:et.heading==="What's Happening"?null:et.heading==="Next Steps (Once Complete)"?{...et,heading:"Next Steps"}:et).filter(Boolean)||[]}}:null))}catch(je){console.error("[Debug Setup] Error polling queue:",je)}},de=setInterval(()=>{be().catch(()=>{})},2e3);return()=>{clearInterval(de)}}else console.warn("[Debug Setup] No job ID returned from debug setup!")}else xe.data.error&&(console.error("[Debug Setup] Error:",xe.data.error),alert(`Debug setup failed: ${xe.data.error}`))},[xe.state,xe.data]),G(()=>{Re.state==="idle"&&Re.data&&(Re.data.success?setTimeout(()=>{Y(Date.now()),ye.revalidate(),T(!1)},1500):Re.data.error&&(T(!1),alert(`Recapture failed: ${Re.data.error}`)))},[Re.state,Re.data,ye]);const Ge=()=>{d&&we.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},jt=async()=>{Ee(!0);try{const{default:Q}=await import("html2canvas-pro"),de=(await Q(document.body)).toDataURL("image/jpeg",.8);re(de),q(!0)}catch(Q){console.error("Screenshot capture failed:",Q),q(!0)}finally{Ee(!1)}},$t=()=>{q(!1),re(null)};G(()=>{we.state==="idle"&&we.data&&(we.data.success?ye.revalidate():we.data.error&&alert(`Analysis failed: ${we.data.error}`))},[we.state,we.data,d?.sha,ye]),G(()=>{const Q=setTimeout(()=>{ye.revalidate()},500);return()=>clearTimeout(Q)},[]),G(()=>{if(gt||Rt){const Q=setInterval(()=>{ye.revalidate()},3e3);return()=>clearInterval(Q)}else{const Q=setInterval(()=>{ye.revalidate()},5e3),be=setTimeout(()=>{clearInterval(Q)},3e4);return()=>{clearInterval(Q),clearTimeout(be)}}},[gt,Rt,ye]);const Dt=(Q,be)=>Q==="scenarios"?`/entity/${d?.sha}/scenarios`:`/entity/${d?.sha}/${Q}`,ae=(Q,be)=>`/entity/${d?.sha}/scenarios/${Q}/${be}`,_e=Q=>{I(Q),S?.id&&x(ae(S.id,Q),{replace:!0})},Ce=d?Zn(d):!1,yt=m!==null;return n(un,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("button",{onClick:w,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-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:d?.name}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d?.filePath,children:d?.filePath})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[It?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(He,{size:14,className:"animate-spin"}),"Analyzing..."]}):Tt?c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#f3e5f5] border border-[#ce93d8] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#9c27b0]"}),n("span",{className:"text-xs font-semibold text-[#6a1b9a]",children:"Queued"})]}):yt?Ce?c(te,{children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#e3f2fd] border border-[#90caf9] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#2196f3]"}),n("span",{className:"text-xs font-semibold text-[#1976d2]",children:"Out of date"})]}),n("button",{onClick:Ge,disabled:we.state!=="idle",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 disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})]}):c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#e8f5e9] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#4caf50]"}),n("span",{className:"text-xs font-semibold text-[#2e7d32]",children:"Up to date"})]}):c(te,{children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{onClick:Ge,disabled:we.state!=="idle",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 disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})]}),c("button",{onClick:()=>{jt()},disabled:se,className:"flex items-center gap-1.5 px-2 py-1 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors disabled:opacity-50 disabled:cursor-wait",title:"Report an issue with this entity",children:[se?n(He,{size:14,className:"animate-spin"}):n(kn,{size:14}),n("span",{className:"text-xs",children:se?"Capturing...":"Report"})]})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#e1e1e1] shrink-0",children:n("div",{className:"flex items-center gap-6 h-10 px-[15px] shrink-0",children:[{id:"scenarios",label:"Scenarios",count:b.length},{id:"related",label:"Related Entities",count:h.importedEntities.length+h.importingEntities.length},{id:"data",label:"Data Structure"},{id:"code",label:"Code"},{id:"history",label:"History"}].map(Q=>c(ee,{to:Dt(Q.id),className:`flex items-center justify-center gap-3 shrink-0 text-sm rounded-md transition-colors no-underline ${C===Q.id?"bg-[#343434] text-[#efefef] font-medium h-8 px-6":"text-[#3e3e3e] font-normal hover:bg-gray-100 py-1 px-[15px]"}`,children:[Q.label,Q.count!==void 0&&n("span",{className:`w-[25px] h-5 rounded-md text-xs font-normal flex items-center justify-center ${C===Q.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:Q.count})]},Q.id))})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[C==="scenarios"&&c(te,{children:[n(Sd,{scenarios:b,analysis:m,selectedScenario:S,entitySha:d?.sha||"",cacheBuster:L,activeTab:C,entityType:d?.entityType,entity:d,queueState:v,processIsRunning:E,viewMode:A,setViewMode:_e,onDebugSetup:()=>{!S?.id||!m?.id||xe.submit({analysisId:m.id,scenarioId:S.id},{method:"post",action:"/api/debug-setup"})},debugFetcher:xe}),n(_a,{selectedScenario:S,analysis:m,entity:d,viewMode:A,cacheBuster:L,hasScenarios:b.length>0,isAnalyzing:Rt,projectSlug:u,hasAnApiKey:y})]}),C==="related"&&n(Id,{relatedEntities:h}),C==="data"&&n(Dd,{entity:d,analysis:m,scenarios:b,onAnalyze:Ge}),C==="code"&&n(zd,{entity:d,entityCode:p}),C==="history"&&n(kd,{entity:d,history:f})]}),j&&u&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>U(!1),children:c("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:Q=>Q.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>U(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(ut,{projectSlug:u,onClose:()=>U(!1)})})]})}),B&&J&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>H(!1),children:c("div",{className:"bg-white rounded-xl max-w-[800px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:Q=>Q.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("div",{className:"flex items-center gap-3",children:n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:J.instructions?.title||"Debug Environment Ready"})}),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:()=>H(!1),children:"×"})]}),n("div",{className:"px-6 py-6 overflow-y-auto flex-1",children:n("div",{className:"p-0",children:J.instructions?.sections?.map((Q,be)=>c("div",{className:"mb-6 last:mb-0",children:[c("h3",{className:"text-base font-semibold text-gray-900 m-0 mb-3 pb-2 border-b-2 border-gray-200 flex items-center gap-2",children:[Q.heading==="Status"&&!J.complete&&n("div",{className:"w-6 h-6 border-3 border-purple-600 border-t-transparent rounded-full animate-spin",style:{borderWidth:"3px"}}),Q.heading]}),Q.items.map((de,je)=>c("div",{className:"mb-3 pl-0 last:mb-0",children:[de.label&&n("div",{className:"font-semibold text-gray-700 mb-1 text-sm",children:de.label}),de.isCode?c("div",{className:"relative mt-1",children:[n("code",{className:"block bg-gray-800 text-gray-50 px-3 py-2.5 pr-[90px] rounded-md text-[13px] font-mono overflow-x-auto",children:de.content}),n(rn,{content:de.content,label:"📋 Copy",className:"absolute top-2 right-2 px-2.5 py-1 bg-purple-600/90 text-white border-none rounded text-[11px] font-semibold cursor-pointer transition-all backdrop-blur hover:bg-purple-700/95 hover:scale-105 active:scale-95 disabled:opacity-75 disabled:cursor-not-allowed disabled:scale-100"})]}):de.isLink?c("div",{className:"flex items-center gap-2 mt-1",children:[n("a",{href:de.content,target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-800 underline text-sm font-medium",children:de.content}),n(rn,{content:de.content,label:"📋",className:"px-2 py-1 bg-gray-200 text-gray-700 border-none rounded text-[11px] font-semibold cursor-pointer transition-all hover:bg-gray-300 hover:scale-105 active:scale-95"})]}):n("div",{className:"text-gray-600 text-sm leading-relaxed",children:de.content})]},je))]},be))})}),n("div",{className:"px-6 py-6 border-t border-gray-200 flex justify-end gap-3",children:n("button",{className:"px-5 py-2.5 bg-gray-500 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-gray-600",onClick:()=>H(!1),children:"Close"})})]})}),n(On,{isOpen:$,onClose:$t,context:{source:S?"scenario-page":"entity-page",entitySha:d?.sha,scenarioId:S?.id,analysisId:m?.id,currentUrl:typeof window<"u"?window.location.pathname:`/entity/${d?.sha}`},defaultEmail:kt,screenshotDataUrl:X??void 0})]})})}),Gd=Object.freeze(Object.defineProperty({__proto__:null,default:Wd,loader:qd,meta:Bd,shouldRevalidate:Ud},Symbol.toStringTag,{value:"Module"}));async function Hd(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:s,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Ae();const i=ie();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=le.join(i,".codeyam","config.json"),d=JSON.parse(await ge.readFile(l,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const h=`/tmp/codeyam/local-dev/${m}/codeyam/log.txt`;try{await ge.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Te(m);let g=r;if(!g||g.length===0){console.log("[analyzeEntities] Loading entities to determine file paths...");const b=await lt({shas:t});if(!b||b.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);g=[...new Set(b.map(x=>x.filePath).filter(x=>!!x))],console.log(`[analyzeEntities] Found ${g.length} unique files`)}if(!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const y=await Qo(p,f,g);console.log(`[analyzeEntities] Created commit ${y.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await at({commitSha:y.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),currentEntityShas:t,entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(b,x)=>{if(!b)return;const N=b.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&rc(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:y.sha,projectSlug:m,filePaths:g,entityShas:t,...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Kd({request:e,context:t}){if(e.method!=="POST")return D({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ye()),!r)return D({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(s)m=[s];else return D({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return D({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const{jobId:u}=await Hd({entityShas:m,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${u}`),D({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,jobId:u})}catch(a){return console.error("[API] Error starting analysis:",a),D({error:"Failed to start analysis",details:a.message},{status:500})}}const Vd=Object.freeze(Object.defineProperty({__proto__:null,action:Kd},Symbol.toStringTag,{value:"Module"})),Jd=()=>c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]});function Pa(e,t,r){const a=e.entityType==="visual"||e.entityType==="library",s=(r?.jobs.some(N=>N.entityShas?.includes(e.sha)||N.type==="analysis"&&N.entityShas&&N.entityShas.length===0)??!1)||(r?.currentlyExecuting?.entityShas?.includes(e.sha)??!1),o=t?.currentEntityShas?.includes(e.sha)??!1,i=e.analyses?.[0],l=!!i,m=(i?.scenarios||[]).length,u=i?.entitySha===e.sha,h=l&&!u,p=i?.status?.scenarios||[],f=p.filter(N=>N.screenshotFinishedAt).length,g=m>0&&f===m,y=p.some(N=>N.screenshotStartedAt&&!N.screenshotFinishedAt),v=m>0&&!g&&u&&(o||y||!!t?.capturePid);let b,x;return s?(b="queued",x={label:"In Queue",color:"text-[#3098b4]",bgColor:"bg-[#cbf3fa]",icon:n(Wt,{size:14}),shouldAnimate:!1}):o||v?(b=v?"capturing":"analyzing",x={label:"Analyzing...",subtitle:v&&f>0?`(${f}/${m})`:void 0,color:"text-[#ff2ab5]",bgColor:"bg-[#ffdbf6]",icon:n(Jd,{}),shouldAnimate:!0}):h?(b="outdated",x={label:"Out of date",color:"text-[#c69538]",bgColor:"bg-[#fdf9c9]",icon:"⚠",shouldAnimate:!1}):l&&g?(b="up-to-date",x={label:"Up to date",color:"text-[#00925d]",bgColor:"bg-[#e8ffe6]",icon:n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),shouldAnimate:!1}):l&&m===0?(b="analyzed",x={label:"Analyzed",subtitle:"(no scenarios)",color:"text-[#00925d]",bgColor:"bg-[#e8ffe6]",icon:"✓",shouldAnimate:!1}):a?(b="not-analyzed",x={label:"Not analyzed",color:"text-[#646464]",bgColor:"bg-[#f9f9f9]",icon:n("div",{className:"w-2 h-2 rounded-full border border-[#646464]"}),shouldAnimate:!1}):(b="not-analyzable",x=null),{isQueued:s,isAnalyzing:o,isCapturing:v,hasAnalysis:l,hasScenarios:m>0,isOutdated:h,canBeAnalyzed:a,scenariosCaptured:f,totalScenarios:m,captureProgress:m>0?Math.round(f/m*100):0,status:b,badge:x}}function Qd({entity:e,variant:t="default",currentRun:r,queueState:a}){const s=Pa(e,r,a);return s.badge?t==="compact"?s.isOutdated?n("div",{className:"bg-[#fdf9c9] px-2 py-0 h-[20px] rounded flex items-center text-[10px] leading-[15px] font-medium text-[#c69538]",children:"Out of date"}):c("div",{className:"flex items-center gap-1.5 bg-[#e8ffe6] px-2 py-0 h-[20px] rounded text-[10px] leading-[15px] font-medium text-[#00925d]",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),"Up to date"]}):c("div",{className:`flex items-center gap-1.5 px-2 py-0 h-[20px] rounded ${s.badge.bgColor}`,children:[typeof s.badge.icon=="string"?n("span",{className:"text-xs",children:s.badge.icon}):s.badge.icon,c("span",{className:`text-[10px] leading-[15px] font-medium ${s.badge.color}`,children:[s.badge.label,s.badge.subtitle&&n("span",{className:"opacity-75 ml-1",children:s.badge.subtitle})]})]}):null}const Zd="data:image/svg+xml,%3csvg%20width='35'%20height='35'%20viewBox='0%200%2035%2035'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='35'%20height='35'%20rx='4'%20fill='%239040F5'/%3e%3cpath%20d='M26.6995%2024.0683V18.306L21.2533%2012.835L14.5785%2019.5423L12.4946%2017.4919L8.29688%2021.6596V24.0683H26.6995Z'%20fill='%23F3EEFE'/%3e%3ccircle%20cx='12.4044'%20cy='13.4307'%20r='2.49813'%20fill='%23F3EEFE'/%3e%3c/svg%3e",Xd=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function eu({request:e}){try{const t=await Mt();return D({entities:t||[]})}catch(t){return console.error("Failed to load simulations:",t),D({entities:[],error:"Failed to load simulations"})}}const tu=Ie(function(){const r=De().entities,[a,s]=k(""),[o,i]=k("visual"),[l,d]=k(null),m=ne(()=>{const C=[];return r.forEach(S=>{const A=S.analyses?.[0];if(A?.scenarios){const I=A.scenarios.filter(R=>R.metadata?.screenshotPaths?.[0]).map(R=>({scenarioName:R.name,scenarioDescription:R.description||"",screenshotPath:R.metadata?.screenshotPaths?.[0]||"",scenarioId:R.id}));I.length>0&&C.push({entity:S,screenshots:I,createdAt:A.createdAt||""})}}),C.sort((S,A)=>new Date(A.createdAt).getTime()-new Date(S.createdAt).getTime()),C},[r]),u=ne(()=>r.filter(C=>!C.analyses?.[0]?.scenarios?.some(I=>I.metadata?.screenshotPaths?.[0])),[r]),h=ne(()=>m.filter(({entity:C})=>{const S=!a||C.name.toLowerCase().includes(a.toLowerCase()),A=o==="all"||C.entityType===o;return S&&A}),[m,a,o]),p=ne(()=>u.filter(C=>{const S=!a||C.name.toLowerCase().includes(a.toLowerCase()),A=o==="all"||C.entityType===o;return S&&A}),[u,a,o]),f=ne(()=>{const C=[];return h.forEach(({entity:S,screenshots:A})=>{A.forEach(I=>{C.push({entitySha:S.sha,entityName:S.name,scenarioId:I.scenarioId||"",scenarioName:I.scenarioName,scenarioDescription:I.scenarioDescription,screenshotPath:I.screenshotPath})})}),C},[h]),g=Z(C=>{s(C.target.value)},[]),y=Z(C=>{i(C.target.value)},[]),v=Z((C,S)=>{const A=f.findIndex(I=>I.entitySha===C&&I.scenarioId===S);A!==-1&&d(A)},[f]),b=Z(()=>{d(null)},[]),x=Z(()=>{d(C=>C===null||C===0?f.length-1:C-1)},[f.length]),N=Z(()=>{d(C=>C===null?0:(C+1)%f.length)},[f.length]);G(()=>{if(l===null)return;const C=S=>{S.key==="Escape"?b():S.key==="ArrowLeft"?x():S.key==="ArrowRight"&&N()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[l,b,x,N]);const w=m.length>0,E=l!==null?f[l]:null;return c("div",{className:"bg-[#f9f9f9] min-h-screen overflow-y-auto",children:[c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 m-0",children:"Simulations"}),n("p",{className:"text-sm text-gray-600 mt-2",children:"All recently captured simulations."})]}),!w&&c("div",{className:"rounded-lg px-5 py-6 mb-6 flex items-center gap-4",style:{backgroundColor:"#f3eefe"},children:[n("img",{src:Zd,alt:"",className:"rounded shrink-0",style:{width:"35px",height:"35px"}}),c("div",{children:[n("p",{className:"text-sm m-0 mb-1",style:{color:"#9040f5"},children:"This page will display a visual gallery of your recently captured component screenshots."}),n("p",{className:"text-sm font-semibold m-0",style:{color:"#9040f5"},children:"Start by analyzing your first component below."})]})]}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[10px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 py-2 pr-8 text-sm cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:o,onChange:y,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Sn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Xa,{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 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:g})]})]})]}),c("div",{className:"flex flex-col gap-3",children:[w&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):c(te,{children:[h.map(({entity:C,screenshots:S})=>n(ru,{entity:C,screenshots:S,onScreenshotClick:v},C.sha)),n("div",{className:"bg-white border-x border-b border-gray-200 rounded-b-lg px-5 py-4 text-center",children:n(ee,{to:"/files?entityType=visual",className:"text-sm text-[#005c75] hover:text-[#004a5e] hover:underline",children:"Find more entities to simulate →"})})]})),!w&&(p.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."}):p.map(C=>n(au,{entity:C},C.sha)))]})]}),E&&n(nu,{screenshot:E,currentIndex:l,totalCount:f.length,onClose:b,onPrevious:x,onNext:N})]})});function nu({screenshot:e,currentIndex:t,totalCount:r,onClose:a,onPrevious:s,onNext:o}){const i=ct(),[l,d]=k(!1),m=()=>{i(`/entity/${e.entitySha}/scenarios/${e.scenarioId}?from=simulations`)};return n("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",onClick:a,children:c("div",{className:"relative flex flex-col w-[90vw] h-[90vh] max-w-[1400px] bg-white rounded-lg overflow-hidden",onClick:u=>u.stopPropagation(),children:[c("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 bg-gray-50 shrink-0",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-sm text-gray-500",children:[t+1," of ",r]}),n("span",{className:"text-gray-300",children:"|"}),n("span",{className:"text-sm font-medium text-gray-700",children:e.entityName})]}),n("button",{onClick:a,className:"p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-200 rounded-full transition-colors cursor-pointer",children:n(es,{className:"w-5 h-5"})})]}),c("div",{className:"relative flex-1 flex items-center justify-center p-6 bg-gray-100 overflow-hidden",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[n("button",{onClick:s,className:`absolute left-4 z-10 p-3 bg-white/90 hover:bg-white rounded-full shadow-lg transition-all cursor-pointer ${l?"opacity-100":"opacity-0"}`,children:n(ts,{className:"w-6 h-6 text-gray-700"})}),n("div",{className:"flex items-center justify-center w-full h-full cursor-pointer",onClick:m,children:n(Se,{screenshotPath:e.screenshotPath,alt:e.scenarioName,className:"max-w-full max-h-full object-contain rounded-lg shadow-lg"})}),n("button",{onClick:o,className:`absolute right-4 z-10 p-3 bg-white/90 hover:bg-white rounded-full shadow-lg transition-all cursor-pointer ${l?"opacity-100":"opacity-0"}`,children:n(rr,{className:"w-6 h-6 text-gray-700"})})]}),c("div",{className:"px-6 py-4 border-t border-gray-200 bg-white cursor-pointer hover:bg-gray-50 transition-colors shrink-0",onClick:m,children:[c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-lg font-semibold text-[#005c75] hover:text-[#004a5e] m-0 mb-1",children:e.scenarioName}),n("p",{className:"text-sm text-gray-600 m-0 line-clamp-2 min-h-10",children:e.scenarioDescription||" "})]}),c("div",{className:"shrink-0 flex items-center gap-1 text-sm text-[#005c75]",children:[n("span",{children:"View details"}),n(rr,{className:"w-4 h-4"})]})]}),n("p",{className:"text-xs text-gray-400 mt-2 m-0",children:"Click to view this scenario in the entity page"})]})]})})}function ru({entity:e,screenshots:t,onScreenshotClick:r}){const a=ct();e.entityType;const s=t.length||(e.analyses?.[0]?.scenarios?.length??0),o=i=>{a(`/entity/${e.sha}/scenarios/${i}?from=simulations`)};return n("div",{className:"bg-white border-x border-b border-gray-200 first:border-t last:rounded-b-lg hover:bg-gray-100 transition-colors",children:c("div",{className:"px-5 py-4",children:[c("div",{className:"flex items-center justify-between",children:[c(ee,{to:`/entity/${e.sha}`,className:"flex items-center gap-2 no-underline",children:[n(Be,{type:e.entityType}),c("span",{className:"text-xs font-medium text-gray-800",children:[e.name," (",s,")"]})]}),n(Qd,{entity:e,variant:"compact"})]}),n("div",{className:"flex gap-2.5 mt-3 overflow-x-auto pb-1",children:t.length>0?t.map(i=>n("button",{onClick:()=>o(i.scenarioId||""),className:"shrink-0 block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border border-gray-200 overflow-hidden bg-gray-100 flex items-center justify-center transition-all",style:{"--hover-border":"#005C75"},onMouseEnter:l=>{l.currentTarget.style.borderColor="#005C75",l.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)"},onMouseLeave:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none"},children:n(Se,{screenshotPath:i.screenshotPath,alt:i.scenarioName,className:"max-w-full max-h-full object-contain"})})},i.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function au({entity:e}){const t=ue(),[r,a]=k(!1);e.entityType;const s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};G(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]);const o=i=>{if(!i)return"";const l=new Date(i),d=new Date;return l.toDateString()===d.toDateString()?`Today, ${l.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0}).toLowerCase()}`:l.toLocaleDateString("en-US",{month:"short",day:"numeric"})};return n("div",{className:"bg-white border-x border-b border-gray-200 first:border-t last:rounded-b-lg hover:bg-gray-100 transition-colors cursor-pointer",onClick:s,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Be,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(ee,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:o(e.createdAt)}),n("div",{className:"w-24 flex justify-end",children:n("button",{onClick:s,disabled:r||t.state!=="idle",className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Analyzing...":"Analyze"})})]})})}const su=Object.freeze(Object.defineProperty({__proto__:null,default:tu,loader:eu,meta:Xd},Symbol.toStringTag,{value:"Module"}));function ou({request:e,context:t}){const r=t.dbNotifier;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(s){const o=new TextEncoder;s.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
163
+
164
+ `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
165
+
166
+ `))}catch{l()}};r.on("change",d);const m=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
167
+
168
+ `))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const iu=Object.freeze(Object.defineProperty({__proto__:null,loader:ou},Symbol.toStringTag,{value:"Module"}));function Ke(){const e=process.memoryUsage(),t=Is.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(An.totalmem()/1024/1024),freeMemory:Math.round(An.freemem()/1024/1024)}}}function lu(){const e=Ke();console.log(`
169
+ [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 cu(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Ke();global.gc();const t=Ke(),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 du(){const e=Ke(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},a=[];return r.highHeapUsage&&a.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:a,hasIssues:a.length>0}}function uu({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const a=cu(),s=Ke();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:s})}case"detailed":{const a=lu();return Response.json({success:!0,stats:a})}case"leaks":{const a=du(),s=Ke();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=Ke();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory?action=detailed - Log detailed stats to console",leaks:"/api/memory?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const mu=Object.freeze(Object.defineProperty({__proto__:null,loader:uu},Symbol.toStringTag,{value:"Module"}));async function hu({request:e,context:t}){let r=t.analysisQueue;if(r||(r=await Ye()),!r)return D({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return D({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const o=a.searchParams.get("jobId");if(!o)return D({error:"Missing jobId parameter for job query"},{status:400});const i=r.getState();if(i.currentlyExecuting?.id===o)return D({jobId:o,status:"running",job:i.currentlyExecuting});const l=i.jobs.find(m=>m.id===o);if(l){const m=i.jobs.indexOf(l);return D({jobId:o,status:"queued",position:m,job:l})}const d=r.getJobResult(o);return d?D({jobId:o,status:d.status==="error"?"failed":"completed",error:d.error}):D({jobId:o,status:"completed"})}if(s==="full"){const o=r.getState(),i=await Promise.all(o.jobs.map(async d=>{const m=[];if(d.entityShas&&d.entityShas.length>0){const u=d.entityShas.map(p=>Le(p)),h=await Promise.all(u);m.push(...h.filter(p=>p!==null))}return{id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:m,filePaths:d.filePaths}}));let l;if(o.currentlyExecuting){const d=o.currentlyExecuting,m=[];if(d.entityShas&&d.entityShas.length>0){const u=d.entityShas.map(p=>Le(p)),h=await Promise.all(u);m.push(...h.filter(p=>p!==null))}l={id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:m,filePaths:d.filePaths}}return D({state:{...o,jobsWithEntities:i,currentlyExecutingWithEntities:l}})}return D({error:"Unknown queryType"},{status:400})}async function pu({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?.analysisQueue);let r=t.analysisQueue;if(r||(r=await Ye(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),D({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:s,...o}=a;if(console.log("[Queue API] Action:",s,"Params:",Object.keys(o)),s==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),D({jobId:i,status:"queued"})}return s==="resume"?(r.resume(),D({status:"resumed"})):s==="pause"?(r.pause(),D({status:"paused"})):D({error:"Unknown action"},{status:400})}const fu=Object.freeze(Object.defineProperty({__proto__:null,action:pu,loader:hu},Symbol.toStringTag,{value:"Module"})),gu=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],yu=Ie(function(){return ue(),n(un,{children:c("div",{className:"h-screen bg-[#f9f9f9] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(_a,{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})]})]})})}),xu=Object.freeze(Object.defineProperty({__proto__:null,default:yu,meta:gu},Symbol.toStringTag,{value:"Module"})),bu=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function vu({request:e}){try{const t=await ra();if(!t)return D({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=ie()||process.cwd(),a=await dn(r),s=Ca(t.projectSlug);return D({config:t,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:s,error:null})}catch(t){return console.error("Failed to load config:",t),D({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}async function wu({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("groqApiKey"),s=t.get("anthropicApiKey"),o=t.get("openAiApiKey"),i=t.get("pathsToIgnore");let l;if(r)try{l=JSON.parse(r)}catch{return D({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let d;if(i&&(d=i.split(",").map(h=>h.trim()).map(h=>h.startsWith('"')&&h.endsWith('"')||h.startsWith("'")&&h.endsWith("'")?h.slice(1,-1):h).filter(h=>h.length>0)),!await oa({universalMocks:l,pathsToIgnore:d}))return D({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let u=!1;if(a!==void 0||s!==void 0||o!==void 0){const h=ie()||process.cwd(),p=await dn(h);u=a!==void 0&&a!==(p.GROQ_API_KEY||"")||s!==void 0&&s!==(p.ANTHROPIC_API_KEY||"")||o!==void 0&&o!==(p.OPENAI_API_KEY||""),await Xo(h,{...p,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:o||void 0},!0)}return D({success:!0,error:null,requiresRestart:u})}catch(t){return console.log("[Settings Action] Failed to save config:",t),D({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Cu(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Tr({mock:e,onSave:t,onCancel:r}){const[a,s]=k(e.entityName),[o,i]=k(e.filePath),[l,d]=k(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:u=>s(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., packages/supabase/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:l})},className:"px-4 py-2 bg-blue-600 text-white border-none rounded text-sm cursor-pointer hover:bg-blue-700",children:"Save"})]})]})}function Nu(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Su=Ie(function(){const{config:t,secrets:r,versionInfo:a,error:s}=De(),o=Ya(),i=ue(),l=dt(),[d,m]=k(t?.universalMocks||[]),[u,h]=k((t?.pathsToIgnore||[]).join(", ")),[p,f]=k((t?.pathsToIgnore||[]).join(", ")),[g,y]=k(r?.GROQ_API_KEY||""),[v,b]=k(r?.ANTHROPIC_API_KEY||""),[x,N]=k(r?.OPENAI_API_KEY||""),[w,E]=k(!1),[C,S]=k(!1),[A,I]=k(!1),[R,M]=k(!1),[P,F]=k(!1),[_,T]=k(!1),[L,Y]=k(null),[J,O]=k(!1);G(()=>{if(t){m(t.universalMocks||[]);const $=(t.pathsToIgnore||[]).join(", ");h($),f($)}r&&(y(r.GROQ_API_KEY||""),b(r.ANTHROPIC_API_KEY||""),N(r.OPENAI_API_KEY||""))},[t,r]),G(()=>{if(o?.success){M(!0);const $=setTimeout(()=>M(!1),3e3);return()=>clearTimeout($)}},[o]),G(()=>{if(i.state==="idle"&&i.data&&!_){console.log("[Settings] Fetcher data:",i.data);const $=i.data;if($.success){console.log("[Settings] Save successful, revalidating..."),M(!0),T(!0),(u!==p||$.requiresRestart)&&F(!0),l.revalidate();const q=setTimeout(()=>{M(!1),T(!1)},3e3);return()=>clearTimeout(q)}}},[i.state,i.data,_,l,u,p]);const B=$=>{$.preventDefault();const q=new FormData($.currentTarget);q.set("universalMocks",JSON.stringify(d)),console.log("[Settings] Submitting form data:",{universalMocks:q.get("universalMocks"),openAiApiKey:q.get("openAiApiKey")?"***":"(empty)"}),i.submit(q,{method:"post"})},H=$=>{m([...d,$]),O(!1)},j=($,q)=>{const se=[...d];se[$]=q,m(se),Y(null)},U=$=>{m(d.filter((q,se)=>se!==$))};return s?c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:s})})]}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Settings"}),n("p",{className:"text-sm text-gray-500 mt-2",children:"Project Configuration"})]}),n("div",{className:"max-w-5xl my-8",children:c("form",{onSubmit:B,className:"space-y-6",children:[c("div",{children:[n("h2",{className:"text-xl mb-4 text-gray-800 font-semibold",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t?.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map(($,q)=>n("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded",children:c("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:$.path==="."?"Root":$.path})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:$.framework})]}),$.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:$.appDirectory})]}),$.startCommand&&c("div",{className:"col-span-2",children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[$.startCommand.command," ",$.startCommand.args?.join(" ")]})]})]})},q))}):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`."})]}),c("div",{className:"mb-8",children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider Configuration"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:w?"text":"password",id:"groqApiKey",name:"groqApiKey",value:g,onChange:$=>y($.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-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>E(!w),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",children:w?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:C?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:$=>b($.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>S(!C),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",children:C?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-gray-50",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," $2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-blue-100 text-blue-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:x,onChange:$=>N($.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-blue-600 focus:ring-1 focus:ring-blue-600"}),n("button",{type:"button",onClick:()=>I(!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",children:A?"Hide":"Show"})]})]})]})]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"pathsToIgnore",className:"block mb-2 font-medium text-gray-700",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:u,onChange:$=>h($.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-base font-mono focus:outline-none focus:border-blue-600 focus:ring-2 focus:ring-blue-600/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),c("div",{className:"mb-6",children:[c("div",{className:"flex justify-between items-center mb-3",children:[n("label",{className:"block font-medium text-gray-700",children:"Universal Mocks"}),n("button",{type:"button",onClick:()=>O(!0),className:"px-4 py-2 bg-green-600 text-white border-none rounded text-sm cursor-pointer hover:bg-green-700",children:"Add Mock"})]}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),d.length===0?n("div",{className:"p-4 bg-gray-50 rounded text-sm text-gray-500 text-center",children:"No universal mocks configured"}):n("div",{className:"space-y-3",children:d.map(($,q)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:L===q?n(Tr,{mock:$,onSave:se=>j(q,se),onCancel:()=>Y(null)}):n(te,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:$.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:$.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:$.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(q),className:"px-3 py-1 bg-blue-600 text-white border-none rounded text-sm cursor-pointer hover:bg-blue-700",children:"Edit"}),n("button",{type:"button",onClick:()=>U(q),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},q))})]})]}),c("div",{className:"flex gap-4 items-center",children:[n("button",{type:"submit",disabled:i.state==="submitting",className:"px-8 py-3 bg-blue-600 text-white border-none rounded text-base font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-blue-700 whitespace-nowrap",children:i.state==="submitting"?"Saving...":"Save Settings"}),i.state==="submitting"&&n("span",{className:"text-gray-600 text-sm font-medium",children:"Saving..."}),R&&n("span",{className:"text-emerald-600 text-sm font-medium whitespace-nowrap",children:"Settings saved successfully!"}),P&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-3 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),o?.error&&n("span",{className:"text-red-600 text-sm font-medium",children:o.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const $=i.data;return typeof $.error=="string"?n("span",{className:"text-red-600 text-sm font-medium",children:$.error}):null}return null})()]}),t&&c("div",{className:"mt-8 p-4 bg-gray-50 rounded text-sm",children:[n("h3",{className:"text-base mb-3 text-gray-800 font-semibold",children:"Current Configuration"}),c("dl",{className:"grid grid-cols-[150px_1fr] gap-2 m-0",children:[t.projectSlug&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Project Slug:"}),n("dd",{className:"m-0 text-gray-800",children:t.projectSlug})]}),t.packageManager&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Package Manager:"}),n("dd",{className:"m-0 text-gray-800",children:t.packageManager})]}),t.webapps&&t.webapps.length>0&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Web Applications:"}),n("dd",{className:"m-0 text-gray-800",children:t.webapps.map(($,q)=>c("div",{className:"mb-2",children:[n("div",{className:"font-semibold",children:$.path==="."?"Root":$.path}),c("div",{className:"text-sm text-gray-600",children:["Framework: ",$.framework]}),$.startCommand&&c("div",{className:"text-sm text-gray-600 font-mono",children:["Command:"," ",Cu($.startCommand)]})]},q))})]})]})]}),a&&c("div",{className:"mt-8 p-4 bg-gray-50 rounded text-sm",children:[n("h3",{className:"text-base mb-3 text-gray-800 font-semibold",children:"Version Information"}),c("dl",{className:"grid grid-cols-[180px_1fr] gap-2 m-0",children:[a.webserverVersion&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Webserver:"}),n("dd",{className:"m-0 text-gray-800 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Analyzer Template:"}),c("dd",{className:"m-0 text-gray-800",children:[n("span",{className:"font-mono",children:a.templateVersion.version||a.templateVersion.gitCommit?.slice(0,7)||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",Nu(a.templateVersion.buildTimestamp),")"]})]})]}),a.cachedAnalyzerVersion&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Cached Analyzer:"}),c("dd",{className:"m-0 text-gray-800",children:[n("span",{className:"font-mono",children:a.cachedAnalyzerVersion.version||a.cachedAnalyzerVersion.gitCommit?.slice(0,7)||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]})]}),!a.cachedAnalyzerVersion&&t?.projectSlug&&c(te,{children:[n("dt",{className:"font-medium text-gray-600",children:"Cached Analyzer:"}),n("dd",{className:"m-0 text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})]})]})}),J&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Tr,{mock:{entityName:"",filePath:"",content:""},onSave:H,onCancel:()=>O(!1)})]})})]})})}),Au=Object.freeze(Object.defineProperty({__proto__:null,action:wu,default:Su,loader:vu,meta:bu},Symbol.toStringTag,{value:"Module"}));async function Eu({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=ie();if(!r)return new Response("Project root not found",{status:500});const s=le.extname(t)!==""?t:`${t}.html`,o=le.join(r,".codeyam","captures","static",s);try{await ge.access(o);let i=await ge.readFile(o);const l=le.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let m=i.toString("utf-8");const u=m.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;m=m.replace(u[0],g)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(m,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const _u=Object.freeze(Object.defineProperty({__proto__:null,loader:Eu},Symbol.toStringTag,{value:"Module"}));function Ma(e,t,r=10){const a=new Map,s=d=>d.entityType==="visual"||d.entityType==="library";for(const d of e)s(d)&&a.set(d.sha,{entity:d,depth:0});const o=new Map;for(const d of t){const m=d.metadata?.importedBy;if(m)for(const u of Object.keys(m))for(const h of Object.keys(m[u])){const{shas:p}=m[u][h];for(const f of p)o.has(d.sha)||o.set(d.sha,new Set),o.get(d.sha).add(f)}}const i=[],l=new Set;for(const d of e)i.push({sha:d.sha,depth:0}),l.add(d.sha);for(;i.length>0;){const{sha:d,depth:m}=i.shift();if(m>=r)continue;const u=o.get(d);if(u)for(const h of u){if(l.has(h))continue;l.add(h);const p=t.find(f=>f.sha===h);if(p){if(s(p)){const f=m+1,g=a.get(h);(!g||f<g.depth)&&a.set(h,{entity:p,depth:f})}i.push({sha:h,depth:m+1})}}}return Array.from(a.values()).sort((d,m)=>d.depth!==m.depth?d.depth-m.depth:d.entity.name.localeCompare(m.entity.name))}function an(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const s=a.sort((o,i)=>{const l=o.metadata?.editedAt||o.createdAt||"";return(i.metadata?.editedAt||i.createdAt||"").localeCompare(l)});r.push(s[0])}return r}function ka(e,t){const r=new Map,a=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&a.add(s.oldPath);for(const s of e){const o=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),i=o.filter(d=>a.has(d.filePath)&&d.metadata?.isUncommitted&&!d.metadata?.isSuperseded),l=an(i);r.set(s.path,{status:s,entities:o,editedEntities:l})}return r}function Pu(e,t,r){const a=new Map;if(!r){for(const o of e)if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),l=an(i);a.set(o.path,{status:o,entities:l})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&s.set(o.filePath,i)}for(const o of e){const i=s.get(o.path);if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],d=an(l);a.set(o.path,{status:o,entities:d})}}return a}function Mu(e,t){const r=new Map,a=Ta(e,t);for(const s of a){const i=Ma([s],t).filter(({depth:l})=>l>0);r.set(s.sha,i)}return r}function ku(e,t){const r=new Map;for(const a of e){const o=Ma([a],t).filter(({depth:i})=>i>0);r.set(a.sha,o)}return r}function Ta(e,t){const r=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&r.add(s.oldPath);const a=t.filter(s=>r.has(s.filePath)&&s.metadata?.isUncommitted&&!s.metadata?.isSuperseded);return an(a)}const Tu=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Iu({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},[s,o,i]=await Promise.all([Mt(),Me(),Xe()]),l=fa(),d=s?ka(l,s):new Map,m=Array.from(d.entries()).sort((A,I)=>A[0].localeCompare(I[0])),u=s?.length||0,h=s?.filter(A=>A.entityType==="visual").length||0,p=s?.filter(A=>A.entityType==="library").length||0,f=s?Ta(l,s):[],g=f.length,y=s?.filter(A=>(A.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length||0,v=s?.reduce((A,I)=>{const R=I.analyses?.[0]?.scenarios?.length||0;return A+R},0)||0,b=s?.reduce((A,I)=>{const M=(I.analyses?.[0]?.scenarios||[]).filter(P=>P.metadata?.screenshotPaths?.[0]).length;return A+M},0)||0,x=[];s?.forEach(A=>{const I=A.analyses?.[0];I?.scenarios&&I.scenarios.forEach(R=>{const M=R.metadata?.screenshotPaths?.[0];M&&x.push({entitySha:A.sha,entityName:A.name,scenarioId:R.id,scenarioName:R.name,screenshotPath:M,createdAt:I.createdAt||""})})}),x.sort((A,I)=>new Date(I.createdAt).getTime()-new Date(A.createdAt).getTime());const N=x.slice(0,16),w=s?.filter(A=>A.entityType==="visual").filter(A=>!A.analyses?.[0]?.scenarios?.some(M=>M.metadata?.screenshotPaths?.[0])).slice(0,8)||[],C=i?.metadata?.currentRun?.currentEntityShas?.length||0,S=a.jobs.length||0;return D({stats:{totalEntities:u,visualEntities:h,libraryEntities:p,uncommittedEntities:g,entitiesWithAnalyses:y,totalScenarios:v,capturedScreenshots:b,currentlyAnalyzing:C,filesOnQueue:S},uncommittedFiles:m,uncommittedEntitiesList:f,recentSimulations:N,visualEntitiesForSimulation:w,projectSlug:o,queueState:a,currentCommit:i})}catch(r){return console.error("Failed to load dashboard data:",r),D({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 Ru=Ie(function(){const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=De(),m=ue(),u=dt(),{showToast:h}=Fn(),[p,f]=k(new Set),[g,y]=k(null),[v,b]=k(!1),[x,N]=k(!1),{lastLine:w,isCompleted:E,resetLogs:C}=Ue(i,!!g),{simulatingEntity:S,scenarios:A,scenarioStatuses:I,allScenariosCaptured:R}=ne(()=>{const j={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return j;const U=o?.find(re=>re.sha===g);if(!U)return j;const $=U.analyses?.[0],q=$?.scenarios||[],se=$?.status?.scenarios||[],Ee=se.filter(re=>re.screenshotFinishedAt).length,X=q.length>0&&Ee===q.length;return{simulatingEntity:U,scenarios:q,scenarioStatuses:se,allScenariosCaptured:X}},[g,o]);G(()=>{(E||R)&&y(null)},[E,R]);const M=d?.metadata?.currentRun,P=new Set(M?.currentEntityShas||[]),F=new Set(l.jobs.flatMap(j=>j.entityShas||[])),_=new Set(l.currentlyExecuting?.entityShas||[]),T=a.filter(j=>j.entityType==="visual"||j.entityType==="library"),L=T.filter(j=>!P.has(j.sha)&&!F.has(j.sha)&&!_.has(j.sha)),Y=()=>{if(L.length===0){h("All entities are already queued or analyzing","info",3e3);return}console.log("Analyzing uncommitted entities not yet queued:",L.length),console.log("Entity SHAs:",L.map(j=>j.sha)),N(!0),h(`Starting analysis for ${L.length} entities...`,"info",3e3),m.submit({entityShas:L.map(j=>j.sha).join(",")},{method:"post",action:"/api/analyze"})};G(()=>{if(m.state==="idle"&&m.data){const j=m.data;j.success?(console.log("[Analyze All] Success:",j.message),h(`Analysis started for ${j.entityCount} entities in ${j.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):j.error&&(console.error("[Analyze All] Error:",j.error),h(`Error: ${j.error}`,"error",8e3),N(!1))}},[m.state,m.data,h]);const J=(j,U)=>{console.log("Simulating entity:",j);const $=o?.find(q=>q.sha===j);y(j),C(),h(`Starting analysis for ${$?.name||"entity"}...`,"info",3e3),m.submit({entitySha:j,filePath:U},{method:"post",action:"/api/analyze"})},O=j=>{f(U=>{const $=new Set(U);return $.has(j)?$.delete(j):$.add(j),$})},B=ne(()=>{const j=new Map;return s.forEach(U=>{const $=U.entitySha;j.has($)||j.set($,[]),j.get($).push(U)}),Array.from(j.entries()).map(([U,$])=>({entitySha:U,entityName:$[0].entityName,scenarios:$}))},[s]),H=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#F59E0B"},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981"},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6"},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9"}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"py-6 px-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[n("div",{children:n("h1",{className:"text-3xl font-bold text-gray-900 m-0 mb-2",children:"CodeYam"})}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:H.map((j,U)=>n(ee,{to:j.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg hover:-translate-y-0.5 no-underline",style:{borderLeft:`4px solid ${j.color}`},children:c("div",{className:"px-6 py-4 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[n("div",{className:"text-xs text-gray-700 font-medium",children:j.label}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 hidden md:flex",style:{color:j.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none flex-shrink-0",style:{backgroundColor:`${j.color}15`},children:[j.iconType==="folder"&&n(ns,{size:20,style:{color:j.color}}),j.iconType==="check"&&n(Ct,{size:20,style:{color:j.color}}),j.iconType==="image"&&n(nt,{size:20,style:{color:j.color}}),j.iconType==="gear"&&n(ot,{size:20,style:{color:j.color}}),j.iconType==="code-xml"&&n(rs,{size:20,style:{color:j.color}})]}),n("div",{className:"text-2xl font-bold text-gray-900 leading-none",children:j.value})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:j.color},children:"View All →"})]})]})},U))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),T.length>0&&n("button",{onClick:Y,disabled:m.state!=="idle"||x||L.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:j=>j.currentTarget.style.backgroundColor="#004560",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||x?"Starting analysis...":L.length===0?"All Queued":`Analyze All (${L.length})`})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([j,U])=>{const $=p.has(j),q=U.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>O(j),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:$?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:j}),c("span",{className:"text-xs text-gray-500",children:[q.length," entit",q.length!==1?"ies":"y"]})]})]})}),$&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:q.length>0?q.map(se=>{const Ee=P.has(se.sha),X=F.has(se.sha)||_.has(se.sha);return c(ee,{to:`/entity/${se.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:re=>re.currentTarget.style.borderColor="#005C75",onMouseLeave:re=>re.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:se.entityType==="visual"?"#8B5CF615":se.entityType==="library"?"#6366F1":"#EC4899"},children:[se.entityType==="visual"&&n(nt,{size:16,style:{color:"#8B5CF6"}}),se.entityType==="library"&&n(Or,{size:16,className:"text-white"}),se.entityType==="other"&&n(Fr,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:se.name}),se.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),se.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),se.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),se.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:se.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[Ee&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(He,{size:14,className:"animate-spin"}),"Analyzing..."]}),!Ee&&X&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!Ee&&!X&&n("button",{onClick:re=>{re.preventDefault(),re.stopPropagation(),h(`Starting analysis for ${se.name}...`,"info",3e3),m.submit({entityShas:se.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:re=>re.currentTarget.style.backgroundColor="#004560",onMouseLeave:re=>re.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},se.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},j)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center bg-gray-50 rounded-lg min-h-[200px] justify-center",children:[c("svg",{width:"52",height:"68",viewBox:"0 0 26 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"mb-4 opacity-40",children:[c("g",{clipPath:"url(#clip0_784_10631)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H18.9423L26.0318 7.14651V31.4562C26.0318 32.8693 24.8863 34.0148 23.4732 34.0148H2.55857C1.14551 34.0148 0 32.8693 0 31.4562V2.55857Z",fill:"#D9D9D9"}),n("path",{d:"M18.9453 7.08081H26.0261L18.9453 0V7.08081Z",fill:"#646464"}),n("line",{x1:"3.92188",y1:"13.3633",x2:"21.7341",y2:"13.3633",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"19.4863",x2:"13.0321",y2:"19.4863",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"25.6016",x2:"21.7341",y2:"25.6016",stroke:"#646464",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10631",children:n("rect",{width:"26",height:"34",fill:"white"})})})]}),n("p",{className:"text-sm font-medium text-gray-400 m-0 mb-2",children:"No Uncommitted Changes."})]})]}),c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),s.length>0&&!g?c(te,{children:[n("div",{className:"space-y-6 mb-5",children:B.map(j=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(nt,{size:16,style:{color:"#8B5CF6"}})}),n(ee,{to:`/entity/${j.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:j.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:j.scenarios.map((U,$)=>n(ee,{to:U.scenarioId?`/entity/${U.entitySha}/scenarios/${U.scenarioId}`:`/entity/${U.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:q=>{q.currentTarget.style.borderColor="#005C75",q.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:q=>{q.currentTarget.style.borderColor="#E5E7EB",q.currentTarget.style.boxShadow="none"},title:`${U.scenarioName}`,children:n(Se,{screenshotPath:U.screenshotPath,alt:U.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},$))})]},j.entitySha))}),n(ee,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:j=>j.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):g?c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[S&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Be,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",S.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:S.filePath})]})]})}),R?c("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),c("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):w?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(He,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):m.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(He,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(He,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map((j,U)=>{const $=j.metadata?.screenshotPaths?.[0],q=I.find(X=>X.name===j.name),se=q?.screenshotStartedAt&&!q?.screenshotFinishedAt;return $?n(ee,{to:`/entity/${g}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(Se,{screenshotPath:$,alt:j.name,title:j.name,className:"max-w-full max-h-full object-contain object-center"})},U):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:`Capturing ${j.name}...`,children:n("span",{className:se?"animate-pulse":"text-gray-400",children:se?"⋯":"⏹️"})},U)})})]}):c("div",{className:"flex flex-col items-center",children:[c("div",{className:"py-12 px-6 text-center bg-gray-50 rounded-lg w-full flex flex-col items-center justify-center min-h-[200px]",children:[n("div",{className:"mb-4 bg-[#efefef] rounded-lg p-3",children:n(nt,{size:28,style:{color:"#999999"},strokeWidth:1.5})}),n("p",{className:"text-gray-700 m-0 font-semibold",children:"Start by analyzing your first component below."})]}),(o?.length??0)>0?n(te,{children:n("div",{className:"flex flex-col gap-3 mt-6 w-full",children:(g&&S?[S]:o||[]).map(j=>n("div",{className:"flex flex-col gap-3",children:c("div",{className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg transition-colors",style:{borderLeft:"4px solid #8B5CF6"},onMouseEnter:U=>{U.currentTarget.style.backgroundColor="#F9FAFB"},onMouseLeave:U=>{U.currentTarget.style.backgroundColor="white"},children:[c(ee,{to:`/entity/${j.sha}`,className:"flex items-center gap-4 flex-1 min-w-0 no-underline",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(nt,{size:16,style:{color:"#8B5CF6"}})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"font-semibold text-gray-900 text-sm mb-1",children:j.name}),n("div",{className:"text-xs text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:j.filePath})]})]}),n("button",{onClick:()=>J(j.sha,j.filePath||""),disabled:m.state!=="idle"||g!==null,className:"px-4 py-2 text-white border-none rounded text-sm font-medium cursor-pointer transition-all whitespace-nowrap shrink-0 disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:U=>U.currentTarget.style.backgroundColor="#004560",onMouseLeave:U=>U.currentTarget.style.backgroundColor="#005C75",title:g?"Please wait for current analysis to complete":"Analyze this entity",children:"Analyze"})]})},j.sha))})}):n("p",{className:"text-base text-gray-600 m-0 mb-6 leading-relaxed mt-6",children:"Run analysis on your visual components to create simulations and capture screenshots"})]})]})]}),v&&i&&n(ut,{projectSlug:i,onClose:()=>b(!1)})]})})}),ju=Object.freeze(Object.defineProperty({__proto__:null,default:Ru,loader:Iu,meta:Tu},Symbol.toStringTag,{value:"Module"}));function $u({entity:e,currentRun:t,queueState:r}){const a=ue(),s=e.entityType==="visual"||e.entityType==="library",o=Pa(e,t,r),i=e.analyses?.[0],l=i?.status,d=i?.scenarios||[],m=Z(()=>{a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})},[e,a]),u=Zn(e),h=e.metadata?.isSuperseded===!0,p=o.isAnalyzing||o.isCapturing,f=p||o.isQueued;return c("div",{className:"flex flex-col gap-1.5 p-3 rounded-lg transition-all bg-white hover:bg-gray-100",children:[c("div",{className:"flex justify-between items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 overflow-hidden",children:[n(Be,{type:e.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n(ee,{to:`/entity/${e.sha}`,className:"font-semibold text-sm text-gray-900 whitespace-nowrap",children:e.name}),n("div",{className:"px-1 py-0 h-[15px] flex items-center justify-center rounded text-[10px] leading-[15px] uppercase font-semibold",style:{backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"||e.entityType==="type"?"#f9f9f9":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#f9f9f9":"#f3f4f6",color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#06b6d5":e.entityType==="type"?"#db2627":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":"#6b7280"},children:e.entityType||"other"})]}),n("div",{className:"text-xs text-gray-500 mt-0.5 truncate",children:e.filePath}),e.description&&n("div",{className:"text-sm text-gray-600 mt-1 italic",children:e.description})]})]}),n("div",{className:"flex-1 shrink flex justify-end items-center gap-3",children:c("div",{className:"flex items-center gap-3",children:[o.badge&&c("div",{className:`flex items-center gap-1.5 px-2 py-0 h-[26px] rounded ${o.badge.bgColor}`,children:[typeof o.badge.icon=="string"?n("span",{className:"text-xs",children:o.badge.icon}):o.badge.icon,c("span",{className:`text-[10px] leading-[15px] font-medium ${o.badge.color}`,children:[o.badge.label,o.badge.subtitle&&n("span",{className:"opacity-75 ml-1",children:o.badge.subtitle})]})]}),s&&!o.isQueued&&!p&&n("button",{onClick:m,disabled:f,className:`px-[15px] py-0 h-[23px] border-none rounded text-[12px] font-medium transition-all whitespace-nowrap flex items-center justify-center ${f?"cursor-not-allowed opacity-50":"cursor-pointer hover:-translate-y-px"}`,style:{backgroundColor:"#005C75",color:"#ffffff"},onMouseEnter:g=>{f||(g.currentTarget.style.backgroundColor="#004560")},onMouseLeave:g=>{f||(g.currentTarget.style.backgroundColor="#005C75")},title:p?"Analysis in progress":o.isQueued?"Already queued for analysis":"Analyze this entity",children:"Analyze"})]})})]}),d.length>0&&!o.isQueued&&!p&&n("div",{className:"flex gap-2 flex-wrap px-0 mt-3",children:d.slice(0,5).map((g,y)=>{if(!g.id)return null;if(e.entityType==="library")return n(Jn,{scenario:g,entitySha:e.sha,size:"medium",isOutdated:h||u},y);const v=g.metadata?.screenshotPaths?.[0],b=Vn(g,l,p,e.sha,r);if(b.isCaptured){const x=h||u;return n(ee,{to:`/entity/${e.sha}/scenarios/${g.id}`,className:`relative w-20 h-15 border-2 rounded overflow-hidden cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md ${x?"border-[#c69538] bg-[#fdf9c9] hover:border-[#a07a2d]":"border-gray-200 bg-gray-50 hover:border-blue-600"}`,children:n(Se,{screenshotPath:v,alt:g.name,title:g.name,className:"max-w-full max-h-full object-contain object-center"})},y)}else{const x=b.hasError?"text-red-500":"text-gray-400";return n(ee,{to:`/entity/${e.sha}/scenarios/${g.id}`,className:`w-20 h-15 border-2 border-dashed ${b.borderColor} rounded ${b.bgColor} flex items-center justify-center text-2xl`,title:b.title,children:n("span",{className:b.shouldSpin?"animate-pulse":x,children:b.icon})},y)}})})]})}function Du({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i}){const[l,d]=Mn(),[m,u]=k(new Set),[h,p]=k(""),[f,g]=k(!1),[y,v]=k("all"),b=o||"all",x=(_,T=[])=>{if(T.some(B=>B.entityShas?.includes(_.sha)))return"analyzing";if(!_.analyses||_.analyses.length===0)return"not-analyzed";const Y=_.analyses[0],J=Y.createdAt?new Date(Y.createdAt).getTime():0,O=_.metadata?.editedAt?new Date(_.metadata.editedAt).getTime():0;return J>=O?"up-to-date":"out-of-date"},N=ne(()=>{let _=e;return b!=="all"&&(_=_.filter(T=>T.entityType===b)),s==="analyzed"&&(_=_.filter(T=>T.analyses&&T.analyses.length>0)),_},[e,b,s]),w=ne(()=>{const _=new Map,T=new Map,L=new Map;N.forEach(O=>{const B=`${O.filePath}::${O.name}`,H=T.get(B);if(!H)T.set(B,O),L.set(B,[]);else{const j=H.metadata?.editedAt||H.createdAt||"",U=O.metadata?.editedAt||O.createdAt||"";let $=!1;if(U>j)$=!0;else if(U===j){const q=H.createdAt||"";$=(O.createdAt||"")>q}$?(L.get(B).push(H),T.set(B,O)):L.get(B).push(O)}}),T.forEach((O,B)=>{if(!(O.analyses&&O.analyses.length>0)&&O.metadata?.previousVersionWithAnalyses){const U=(L.get(B)||[]).find($=>$.sha===O.metadata?.previousVersionWithAnalyses);U&&U.analyses&&U.analyses.length>0&&(O.analyses=U.analyses)}}),Array.from(T.values()).sort((O,B)=>{const H=!O.metadata?.notExported&&!O.metadata?.namedExport,j=!B.metadata?.notExported&&!B.metadata?.namedExport;return H&&!j?-1:!H&&j?1:0}).forEach(O=>{const B=O.filePath??"No File Path";_.has(B)||_.set(B,{filePath:B,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const H=_.get(B);H.entities.push(O),H.totalCount++,O.metadata?.isUncommitted&&H.uncommittedCount++;const j=O.analyses?.[0]?.scenarios?.length||0;H.simulationCount+=j;const U=O.metadata?.editedAt||O.updatedAt;U&&(!H.lastUpdated||new Date(U)>new Date(H.lastUpdated))&&(H.lastUpdated=U)});const Y=i?.jobs||[];_.forEach(O=>{const B=O.entities.map(H=>x(H,Y));B.includes("analyzing")?O.state="analyzing":B.includes("out-of-date")?O.state="out-of-date":B.includes("not-analyzed")?O.state="not-analyzed":O.state="up-to-date"}),_.forEach(O=>{for(const B of O.entities){if(O.previewScreenshots.length+O.previewLibraryScenarios.length>=3)break;const j=B.analyses?.[0]?.scenarios||[];if(B.entityType==="library"){const U=j.find($=>$.metadata?.executionResult||$.metadata?.error);U&&O.previewLibraryScenarios.push({scenario:U,entitySha:B.sha})}else{const U=j.find($=>$.metadata?.screenshotPaths?.[0]);if(U){const $=U.metadata?.screenshotPaths?.[0],q=!!U.metadata?.error;$&&!O.previewScreenshots.includes($)&&(O.previewScreenshots.push($),O.previewScreenshotErrors.push(q))}}}});const J=Array.from(_.values());return J.sort((O,B)=>{if(s==="analyzed"){const U=Math.max(...O.entities.filter(q=>q.analyses?.[0]?.createdAt).map(q=>new Date(q.analyses[0].createdAt).getTime()),0);return Math.max(...B.entities.filter(q=>q.analyses?.[0]?.createdAt).map(q=>new Date(q.analyses[0].createdAt).getTime()),0)-U}if(O.uncommittedCount>0&&B.uncommittedCount===0)return-1;if(O.uncommittedCount===0&&B.uncommittedCount>0)return 1;const H=O.lastUpdated?new Date(O.lastUpdated).getTime():0;return(B.lastUpdated?new Date(B.lastUpdated).getTime():0)-H}),J},[N,s]),E=ne(()=>{let _=w;if(y!=="all"&&(_=_.filter(T=>T.state===y)),h.trim()){const T=h.toLowerCase();_=_.filter(L=>L.filePath.toLowerCase().includes(T))}return _},[w,h,y]),C=(t-1)*r,S=C+r,A=E.slice(C,S),I=Math.ceil(E.length/r),R=_=>{u(T=>{const L=new Set(T);return L.has(_)?L.delete(_):L.add(_),L})},M=()=>{if(f)u(new Set),g(!1);else{const _=new Set(A.map(T=>T.filePath));u(_),g(!0)}},P=_=>{switch(_){case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"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}}},F=_=>{if(!_)return"Never";const T=new Date(_),L=new Date;if(T.getDate()===L.getDate()&&T.getMonth()===L.getMonth()&&T.getFullYear()===L.getFullYear()){const J=T.getHours(),O=T.getMinutes(),B=J>=12?"pm":"am",H=J%12||12,j=O.toString().padStart(2,"0");return`Today, ${H}:${j} ${B}`}return T.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[10px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:b,onChange:_=>{const T=_.target.value,L=new URLSearchParams(l);T==="all"?L.delete("entityType"):L.set("entityType",T),L.set("page","1"),d(L)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[12px] 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(Sn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-2 h-2 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:y,onChange:_=>v(_.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[12px] 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:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(Sn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-2 h-2 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",children:"🔎"}),n("input",{type:"text",placeholder:"Search component",value:h,onChange:_=>p(_.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[12px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]}),n("button",{onClick:M,className:"px-[10px] h-[39px] border-none rounded text-[12px] font-medium cursor-pointer transition-colors whitespace-nowrap bg-[#005c75] text-white hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed w-[130px]",children:f?"Collapse All":"Expand All"})]})]}),n("div",{className:"bg-[#f5f5f5] rounded-lg mb-2 text-[10px] font-normal leading-[15px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center h-[38px]",style:{width:"160px"},children:n("span",{className:"text-center w-full",children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),n("span",{className:"text-center",style:{width:"127px"},children:"STATE"}),c("div",{className:"flex items-center gap-1",style:{width:"116px"},children:[n("span",{className:"text-left",children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]})]})}),n("div",{className:"flex flex-col gap-3",children:A.map(_=>{const T=m.has(_.filePath),L=_.uncommittedCount>0;return c("div",{className:"bg-white overflow-hidden",style:T?{border:"1px solid #e5e7eb",borderLeft:"4px solid #306AFF",borderRadius:"8px"}:{borderRadius:"8px"},children:[c("div",{className:"flex justify-between items-center p-3 cursor-pointer select-none transition-colors hover:bg-gray-200",style:{outlineColor:"#005C75"},onClick:()=>R(_.filePath),role:"button",tabIndex:0,onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),R(_.filePath))},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"text-xs w-4 inline-flex items-center justify-center shrink-0",style:{color:T?"#3e3e3e":"#c7c7c7",transform:T?"rotate(90deg)":"none"},children:"▶"}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n("span",{className:"font-normal text-gray-900 text-[12px] overflow-hidden text-ellipsis whitespace-nowrap",children:_.filePath}),L&&c("span",{className:"text-[10px] text-amber-500 font-medium shrink-0 whitespace-nowrap",children:[_.uncommittedCount," uncommitted"]})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex gap-1.5 items-center justify-center h-[38px]",style:{width:"160px"},children:[_.previewScreenshots.map((Y,J)=>{const O=_.previewScreenshotErrors[J];return c("div",{className:`relative w-[50px] h-[38px] border ${O?"border-red-400":"border-gray-200"} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center`,children:[n(Se,{screenshotPath:Y,alt:`Preview ${J+1}`,className:"max-w-full max-h-full object-contain object-center"}),O&&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(Cn,{size:12,color:"white"})})]},`screenshot-${J}`)}),_.previewLibraryScenarios.map((Y,J)=>n(Jn,{scenario:Y.scenario,entitySha:Y.entitySha,size:"small",showBorder:!0},`library-${J}`))]}),c("div",{className:"flex gap-3 items-center",children:[n("div",{className:"flex items-center justify-center",style:{minWidth:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"23px"},children:c("span",{className:"text-[12px] text-[#3e3e3e]",children:[_.totalCount," ",_.totalCount===1?"entity":"entities"]})})}),n("div",{className:"flex items-center justify-center",style:{width:"127px"},children:(()=>{const Y=P(_.state);return c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:Y.bgColor,color:Y.textColor,height:"23px"},children:[Y.icon,Y.text]})})()}),n("span",{className:"text-[11px] text-gray-400",style:{width:"116px",textAlign:"center"},children:F(_.lastUpdated)})]})]})]}),T&&n("div",{className:"p-2 bg-gray-50 flex flex-col gap-2",children:_.entities.map(Y=>n($u,{entity:Y,currentRun:a,queueState:i},Y.sha))})]},_.filePath)})}),I>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(l),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",I]}),t<I&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(l),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Lu=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Ou({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),s=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([Mt(),Xe()]);return D({entities:d,currentCommit:m,page:a,filter:s,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),D({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Fu=Ie(function(){const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i}=De(),l=dt(),d=ne(()=>{if(!t)return[];const h=new Set([]);for(const p of t)h.add(p.filePath??"No File Path");return Array.from(h)},[t]),m=ne(()=>t?t.sort((h,p)=>h.metadata?.isUncommitted&&!p.metadata?.isUncommitted?-1:!h.metadata?.isUncommitted&&p.metadata?.isUncommitted?1:new Date(p.metadata?.editedAt||0).getTime()-new Date(h.metadata?.editedAt||0).getTime()):[],[t]),u=ne(()=>{if(!t)return[];const h=new Set([]);for(const p of t)p.metadata?.isUncommitted&&h.add(p.filePath??"No File Path");return Array.from(h)},[t]);return t?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Files & Entities"}),c("div",{className:"flex gap-4 text-sm text-gray-500 mt-2",children:[l.state==="loading"&&n("span",{className:"text-blue-600 font-medium animate-pulse",children:"🔄"}),c("span",{children:[d.length," files"]}),c("span",{children:[t.length," entities"]}),c("span",{className:"text-amber-500 font-medium",children:[u.length," uncommitted files"]})]})]}),n(Du,{entities:m,page:a,itemsPerPage:50,currentRun:r?.metadata?.currentRun,filter:s,entityType:o,queueState:i})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:"Unable to retrieve entities"})]})})}),Yu=Object.freeze(Object.defineProperty({__proto__:null,default:Fu,loader:Ou,meta:Lu},Symbol.toStringTag,{value:"Module"}));function zu(e,t,r){const[a,s]=k(()=>new Set(t)),[o,i]=k(()=>new Set(r)),l=fe([]),d=fe([]);return G(()=>{(t.length!==l.current.length||t.some((y,v)=>y!==l.current[v]))&&(l.current=t,s(y=>{const v=new Set(y);return t.forEach(b=>{y.has(b)||v.add(b)}),v}))},[t]),G(()=>{(r.length!==d.current.length||r.some((y,v)=>y!==d.current[v]))&&(d.current=r,i(y=>{const v=new Set(y);return r.forEach(b=>{y.has(b)||v.add(b)}),v}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,v)=>{v(b=>{const x=new Set(b);return x.has(g)?x.delete(g):x.add(g),x})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Bu(e,t,r){const[a,s]=k(null),[o,i]=k(null),l=ue();G(()=>{l.data?.oldContent!==void 0&&l.data?.newContent!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=h=>{s({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType",r==="branch"?"branch":"uncommitted"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},m=(h,p)=>{s({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType",r==="branch"?"branch":"uncommitted"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function Uu(e){const t=ue(),{showToast:r}=Fn();G(()=>{if(t.state==="idle"&&t.data){const i=t.data;i?.error&&r(`Error: ${i.error}`,"error",6e3)}},[t.state,t.data,r]);const a=i=>{console.log("Generate analysis clicked for entity:",i.sha,i.name);const l=new FormData;l.append("entitySha",i.sha),l.append("filePath",i.filePath||""),t.submit(l,{method:"post",action:"/api/analyze"})},s=i=>{const l=i.filter(u=>u.entityType==="visual"||u.entityType==="library");console.log("Generate analysis for all entities:",l.length);const d=l.map(u=>u.sha).join(","),m=new FormData;m.append("entityShas",d),t.submit(m,{method:"post",action:"/api/analyze"})},o=i=>e?.includes(i)??!1;return{isAnalyzing:t.state!=="idle",handleGenerateSimulation:a,handleGenerateAllSimulations:s,isEntityBeingAnalyzed:o}}function qu({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){const[o,i]=k(!1),[l,d]=k(!1);return G(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",a.find(m=>m.sha===e.entitySha)?.name||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors",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(Rs,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:s,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors",children:"Close"})})]})})}function Wu({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200 mb-6",children:c("nav",{className:"flex gap-8 items-center",children:[n("button",{onClick:()=>t("uncommitted"),className:`relative pb-4 px-2 text-sm font-medium transition-colors ${e==="uncommitted"?"text-[#005C75] border-b-2 border-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#e8f1f5] text-[#005C75]":"bg-gray-200 text-gray-700"}`,children:r})]})}),n("button",{onClick:()=>t("branch"),className:`relative pb-4 px-2 text-sm font-medium transition-colors ${e==="branch"?"text-[#005C75] border-b-2 border-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:c("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#e8f1f5] text-[#005C75]":"bg-gray-200 text-gray-700"}`,children:a})]})})]})})}function Gu(e,t){const a=t.match(/text-(\w+)-\d+/)?.[1]||"gray",o={green:"#15803d",gray:"#374151",orange:"#b45309",blue:"#1e40af",amber:"#b45309",purple:"#6b21a8"}[a]||"#374151";switch(e){case"✓":return n(Ct,{size:16,color:o});case"○":return n(ss,{size:16,color:o});case"⚠":return n(In,{size:16,color:o});case"●":return n(Fr,{size:16,color:o});case"+":return n(as,{size:16,color:o});default:return e}}function Hu({entity:e,variant:t="full"}){const r=Ea(e),{badge:a}=r,s=Gu(a.icon,a.color);return t==="icon-only"?n("span",{className:`${a.color} text-sm font-bold`,title:a.label,children:s}):t==="compact"?n("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-normal border ${a.color} ${a.bgColor} ${a.borderColor}`,title:a.label,children:n("span",{children:a.label})}):n("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-normal border ${a.color} ${a.bgColor} ${a.borderColor}`,children:n("span",{children:a.label})})}function Ku({entity:e,filePath:t,impactedEntities:r,isBeingAnalyzed:a,isQueued:s,projectSlug:o,diffType:i,baseBranch:l,currentBranch:d,onGenerateSimulation:m,onShowLogs:u}){const h=e.analyses?.[0],p=h?.scenarios||[],f=h?.status?.scenarios||[];return c("div",{className:"flex flex-col gap-2 p-3 bg-white border border-[#e1e1e1] rounded-md transition-all hover:border-[#005c75] hover:shadow-sm",children:[c("div",{className:"flex items-center gap-2",children:[c(ee,{to:`/entity/${e.sha}`,className:"flex items-center gap-3 flex-1 min-w-0 no-underline",children:[n(Be,{type:e.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"font-['IBM_Plex_Sans'] font-medium text-sm text-[#343434] flex items-center gap-2",children:[n("span",{children:e.name}),e.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),e.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),e.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"}),n(Hu,{entity:e,variant:"full"})]}),e.description&&n("div",{className:"font-['IBM_Plex_Sans'] text-xs text-[#8e8e8e] mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap",children:e.description})]}),c("div",{className:"flex items-center gap-2",children:[a&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[c("svg",{className:"animate-spin h-3.5 w-3.5",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"})]}),"Analyzing..."]}),!a&&s&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"})]})]}),(e.entityType==="visual"||e.entityType==="library")&&!a&&!s&&n("button",{onClick:g=>{g.stopPropagation(),m(e)},className:"px-3 py-1.5 bg-[#005c75] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors whitespace-nowrap",title:"Analyze this entity",children:"Analyze"}),a&&o&&n("button",{onClick:g=>{g.stopPropagation(),u(e.sha)},className:"px-3 py-1.5 bg-[#626262] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-semibold hover:bg-[#4a4a4a] transition-colors whitespace-nowrap",title:"View analysis logs",children:"📋 Logs"})]}),(e.entityType==="visual"||e.entityType==="library")&&p.length>0&&n("div",{className:"flex gap-2.5 mt-3 overflow-x-auto pb-1",children:p.map((g,y)=>{const v=g.metadata?.screenshotPaths?.[0],b=f.find(w=>w.name===g.name),x=b?.screenshotStartedAt&&!b?.screenshotFinishedAt,N=!!v;return n(ee,{to:g.id?`/entity/${e.sha}/scenarios/${g.id}`:`/entity/${e.sha}`,className:"shrink-0 block no-underline",children:n("div",{className:"w-36 h-24 rounded-md border border-gray-200 overflow-hidden bg-gray-100 flex items-center justify-center transition-all",onMouseEnter:w=>{w.currentTarget.style.borderColor="#005C75",w.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)"},onMouseLeave:w=>{w.currentTarget.style.borderColor="#d1d5db",w.currentTarget.style.boxShadow="none"},children:N?n(Se,{screenshotPath:v,alt:g.name,className:"max-w-full max-h-full object-contain"}):n("span",{className:`text-2xl ${x?"animate-pulse":"text-gray-400"}`,children:x?"⋯":"⏹️"})})},y)})})]})}function Vu({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:l,onToggleFile:d,onShowFileDiff:m,onGenerateSimulation:u,onShowLogs:h}){return n("div",{children:e.length>0?n("div",{className:"flex flex-col gap-3",children:e.map(([p,{status:f,editedEntities:g}])=>{const y=r.has(p);return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>d(p),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(p))},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:y?"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:y?"#3e3e3e":"#c7c7c7"})})}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:p}),c("span",{className:"text-xs text-gray-500",children:[g.length," entit",g.length!==1?"ies":"y"]})]})]})}),y&&g.length>0&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:g.map(v=>n(Ku,{entity:v,filePath:p,impactedEntities:t.get(v.sha)||[],isBeingAnalyzed:a(v.sha),isQueued:s(v.sha),projectSlug:o,diffType:"uncommitted",baseBranch:i,currentBranch:l,onGenerateSimulation:u,onShowLogs:h},v.sha))})]},p)})}):c("div",{className:"py-12 px-6 text-center",children:[n("div",{className:"text-6xl mb-4 opacity-50",children:"✓"}),n("p",{className:"font-['IBM_Plex_Sans'] text-lg font-semibold text-[#3e3e3e] mb-2",children:"No edited entities"}),c("p",{className:"font-['IBM_Plex_Sans'] text-sm text-[#8e8e8e]",children:["There are no uncommitted changes.",n("br",{}),n("br",{}),"If you edit a file in the project, it will show up here."]})]})})}function Ju({status:e}){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"}}[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${r.bgColor}`,title:e,children:r.label}),r.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 Qu({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,isAnyAnalysisInProgress:d,isAnalyzing:m,lastLogLine:u,projectSlug:h,onToggleFile:p,onBranchChange:f,onGenerateSimulation:g,onShowLogs:y}){return e.length>0&&e.some(([v,{entities:b}])=>b.length>0),c("div",{children:[n("div",{className:"mb-5",children:t===r?c("p",{className:"text-sm text-gray-500",children:["Currently on the primary branch"," ",n("strong",{className:"text-gray-900 font-semibold",children:t})]}):c("p",{className:"text-sm text-gray-500",children:["Changes in"," ",n("strong",{className:"text-gray-900 font-semibold",children:t})," ","compared to"," ",n("select",{value:a,onChange:v=>f(v.target.value),className:"py-0.5 px-2 bg-white border border-gray-300 rounded-md text-sm font-semibold text-gray-900 cursor-pointer hover:border-indigo-500",children:s.filter(v=>v!==t).map(v=>n("option",{value:v,children:v},v))})]})}),t===r?c("div",{className:"py-12 px-6 text-center bg-blue-50 rounded-lg border border-blue-100",children:[n("div",{className:"text-6xl mb-4",children:"ℹ️"}),n("p",{className:"text-lg font-semibold text-gray-900 mb-3",children:"You're on the primary branch"}),c("p",{className:"text-sm text-gray-600 mb-2 max-w-md mx-auto",children:["When you switch to a feature branch, this section will show all the changes between your branch and"," ",n("strong",{className:"font-semibold",children:r}),"."]}),n("p",{className:"text-sm text-gray-600 max-w-md mx-auto",children:"This helps you understand what will be included in your pull request before you create it."})]}):e.length>0?n("div",{className:"flex flex-col gap-3",children:e.map(([v,{status:b,entities:x}])=>{const N=o.has(v);return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>p(v),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),p(v))},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:N?"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:N?"#3e3e3e":"#c7c7c7"})})}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:v}),n(Ju,{status:b.status})]}),c("span",{className:"text-xs text-gray-500",children:[x.length," entit",x.length!==1?"ies":"y"]})]})]})}),N&&x.length>0&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-2 flex flex-col gap-1.5",children:x.map(w=>{const E=i(w.sha),C=l(w.sha),S=E&&u,A=w.analyses?.[0],I=A?.scenarios||[],R=A?.status?.scenarios||[];return c("div",{className:"flex flex-col gap-2 p-3 bg-white border border-gray-200 rounded-md transition-all hover:border-blue-600 hover:shadow-sm",children:[c("div",{className:"flex items-center gap-2",children:[c(ee,{to:`/entity/${w.sha}`,className:"flex items-center gap-3 flex-1 min-w-0 no-underline",children:[n(Be,{type:w.entityType}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"font-['IBM_Plex_Sans'] font-medium text-sm text-[#343434] flex items-center gap-2",children:[n("span",{children:w.name}),w.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),w.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),w.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),w.description&&n("div",{className:"font-['IBM_Plex_Sans'] text-xs text-[#8e8e8e] mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap",children:w.description})]}),c("div",{className:"flex items-center gap-2",children:[E&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[c("svg",{className:"animate-spin h-3.5 w-3.5",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"})]}),"Analyzing..."]}),!E&&C&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"})]})]}),(w.entityType==="visual"||w.entityType==="library")&&n("button",{onClick:M=>{M.stopPropagation(),g(w)},disabled:m||d||C||E,className:"px-3 py-1.5 bg-[#005c75] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors whitespace-nowrap disabled:bg-gray-400 disabled:cursor-not-allowed",title:C?"Entity is queued for analysis":E?"Entity is being analyzed":d?"Please wait for current analysis to complete":"Analyze this entity",children:E?"Analyzing...":C?"Queued":d?"Waiting...":"Analyze"}),E&&h&&n("button",{onClick:M=>{M.stopPropagation(),y(w.sha)},className:"px-3 py-1.5 bg-[#626262] text-white rounded-md text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#4a4a4a] transition-colors whitespace-nowrap",title:"View analysis logs",children:"📋 Logs"})]}),S&&c("div",{className:"flex items-center gap-1.5 text-[13px] font-medium text-blue-600 px-2 py-1 bg-blue-50 rounded",children:[n("span",{className:"animate-spin",children:"⚙️"}),n("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-xs max-w-full",title:u,children:u})]}),I.length>0&&n("div",{className:"flex gap-2 flex-wrap",children:I.slice(0,5).map((M,P)=>{const F=M.metadata?.screenshotPaths?.[0],_=R.find(J=>J.name===M.name),T=_?.screenshotStartedAt&&!_?.screenshotFinishedAt,L=!!F,Y=Zn(w)||w.metadata?.isSuperseded;return L?n(ee,{to:`/entity/${w.sha}/scenarios/${M.id}`,className:`relative w-20 h-15 border-2 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md ${Y?"border-amber-500 hover:border-amber-600":"border-gray-200 hover:border-blue-600"}`,children:n(Se,{screenshotPath:F,alt:M.name,title:M.name,className:"max-w-full max-h-full object-contain object-center"})},P):n(ee,{to:`/entity/${w.sha}/scenarios/${M.id}`,className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`Capturing ${M.name}...`,children:n("span",{className:T?"animate-spin":"text-gray-400",children:T?"⏳":"⏹️"})},P)})})]},w.sha)})})]},v)})}):c("div",{className:"py-12 px-6 text-center",children:[n("div",{className:"text-6xl mb-4 opacity-50",children:"✓"}),n("p",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No differences found"}),c("p",{className:"text-sm text-gray-500",children:["This branch is up to date with ",a]})]})]})}const Zu=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Xu({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),s=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return s==="branch"?d=Gt(a,o,i):d=Ol(a),D({...d,entitySha:l})}return D({error:"Unknown action"},{status:400})}async function em({request:e,context:t}){try{const a=new URL(e.url).searchParams.get("compare"),s=t.analysisQueue,o=s?s.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([Mt(),Xe(),Me()]),m=fa(),u=Rl(),h=jl(),p=$l(),f=a||h;let g=[];return u&&u!==f&&(g=ga(f,u)),D({entities:i||[],gitStatus:m,currentBranch:u,defaultBranch:h,allBranches:p,baseBranch:f,branchDiff:g,currentCommit:l,projectSlug:d,queueState:o})}catch(r){return console.error("Failed to load git data:",r),D({entities:[],gitStatus:[],currentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const tm=Ie(function(){const{entities:t,gitStatus:r,currentBranch:a,defaultBranch:s,allBranches:o,baseBranch:i,branchDiff:l,currentCommit:d,projectSlug:m,queueState:u}=De(),[h,p]=Mn(),[f,g]=k("uncommitted"),[y,v]=k(null),b=h.get("expanded")==="true",x=ue(),N=x.data;G(()=>{f==="branch"&&a&&i&&a!==i&&x.state==="idle"&&!N&&x.load(`/api/branch-entity-diff?base=${encodeURIComponent(i)}&compare=${encodeURIComponent(a)}`)},[f,a,i,x,N]);const w=ne(()=>{const ae=ka(r,t);return Array.from(ae.entries()).sort((_e,Ce)=>_e[0].localeCompare(Ce[0]))},[r,t]),E=ne(()=>{const ae=Pu(l,t,N);return Array.from(ae.entries()).sort((_e,Ce)=>_e[0].localeCompare(Ce[0]))},[l,t,N]),C=ne(()=>Mu(r,t),[r,t]);ne(()=>{const ae=E.flatMap(([_e,Ce])=>Ce.entities);return ku(ae,t)},[E,t]);const S=ne(()=>w.map(([ae])=>ae),[w]),A=ne(()=>E.map(([ae])=>ae),[E]),{expandedUncommitted:I,expandedBranch:R,setExpandedUncommitted:M,setExpandedBranch:P,toggleFile:F,expandAllUncommitted:_,collapseAllUncommitted:T,expandAllBranch:L,collapseAllBranch:Y}=zu(b,S,A),{diffView:J,diffContent:O,isLoading:B,handleShowFileDiff:H,handleCloseDiff:j}=Bu(i,a,f),U=d?.metadata?.currentRun,$=!!U?.createdAt&&!U?.analysisCompletedAt,{lastLine:q,isCompleted:se}=Ue(m,$),Ee=$&&!se,X=new Set(U?.currentEntityShas||[]),re=new Set(u.jobs.flatMap(ae=>ae.entityShas||[])),me=new Set(u.currentlyExecuting?.entityShas||[]),{isAnalyzing:he,handleGenerateSimulation:kt,handleGenerateAllSimulations:xe,isEntityBeingAnalyzed:Re}=Uu(U?.currentEntityShas),we=ae=>re.has(ae)||me.has(ae),ye=ae=>{ae===s?h.delete("compare"):h.set("compare",ae),p(h)},ft=()=>{const _e=(f==="uncommitted"?w.flatMap(([Ce,yt])=>yt.editedEntities):E.flatMap(([Ce,yt])=>yt.entities)).filter(Ce=>!X.has(Ce.sha)&&!re.has(Ce.sha)&&!me.has(Ce.sha));xe(_e)},gt=w.length,Tt=E.length,It=f==="uncommitted"?gt:Tt,We=(f==="uncommitted"?w.flatMap(([ae,_e])=>_e.editedEntities):E.flatMap(([ae,_e])=>_e.entities)).filter(ae=>ae.entityType==="visual"||ae.entityType==="library"),Ge=We.length>0&&We.every(ae=>X.has(ae.sha)),jt=We.length>0&&!Ge&&We.every(ae=>re.has(ae.sha)||me.has(ae.sha)),$t=he||Ge||jt,Dt=Ge?"Analyzing...":jt?"Queued...":he?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Git Changes"}),n("div",{className:"flex items-center gap-4 text-sm text-gray-600 mt-2",children:a&&c(te,{children:[n("span",{className:"text-xs",children:"Branch:"}),o.length>0?n("select",{value:a,onChange:ae=>ye(ae.target.value),className:"text-gray-900 font-medium px-2 py-1 border border-gray-300 rounded text-sm hover:border-gray-400 focus:outline-none focus:border-blue-500",style:{paddingRight:"26px",backgroundPosition:"right 6px center",backgroundRepeat:"no-repeat",backgroundSize:"16px",appearance:"none",backgroundImage:`url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e")`},children:o.map(ae=>c("option",{value:ae,children:[ae," ",ae===s?"(default)":""]},ae))}):n("span",{className:"text-gray-900 font-medium",children:a})]})})]}),c("div",{className:"flex items-center justify-between mb-1",children:[n(Wu,{activeTab:f,onTabChange:g,uncommittedCount:gt,branchCount:Tt}),It>0&&c("div",{className:"flex gap-2",children:[n("button",{onClick:f==="uncommitted"?_:L,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#626262] hover:text-cyblack-100 hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Expand All"}),n("button",{onClick:f==="uncommitted"?T:Y,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#626262] hover:text-cyblack-100 hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Collapse All"}),n("button",{onClick:ft,disabled:$t,className:"px-4 py-1.5 bg-[#005c75] text-white rounded text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed",title:$t?Dt:`Analyze all ${f} entities`,children:Dt})]})]}),c("div",{className:"overflow-hidden",children:[f==="uncommitted"&&n(Vu,{files:w,entityImpactMap:C,expandedFiles:I,isEntityBeingAnalyzed:Re,isEntityQueued:we,projectSlug:m,baseBranch:i,currentBranch:a,onToggleFile:ae=>F(ae,I,M),onShowFileDiff:H,onGenerateSimulation:kt,onShowLogs:v}),f==="branch"&&a&&n(Qu,{files:E,currentBranch:a,defaultBranch:s,baseBranch:i,allBranches:o,expandedFiles:R,isEntityBeingAnalyzed:Re,isEntityQueued:we,isAnyAnalysisInProgress:Ee,isAnalyzing:he,lastLogLine:q,projectSlug:m,onToggleFile:ae=>F(ae,R,P),onBranchChange:ye,onGenerateSimulation:kt,onShowLogs:v})]}),J&&n(qu,{diffView:J,diffContent:O,isLoading:B,entities:t,onClose:j}),y&&m&&n(ut,{projectSlug:m,onClose:()=>v(null)})]})})}),nm=Object.freeze(Object.defineProperty({__proto__:null,action:Xu,default:tm,loader:em,meta:Zu},Symbol.toStringTag,{value:"Module"})),Wm={entry:{module:"/assets/entry.client-DiP0q291.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/index-D-zYbzFZ.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-DB7VgjCY.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/index-D-zYbzFZ.js","/assets/ReportIssueModal-BORLgi0X.js","/assets/loader-circle-BXPKbHEb.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/settings-5zF_GOcS.js","/assets/useToast-Ddo4UQv7.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/LogViewer-CRcT5fOZ.js","/assets/circle-check-BACUUf75.js","/assets/clock-vWeoCemX.js","/assets/file-text-LM0mgxXE.js","/assets/triangle-alert-D7k-ArFa.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-YJz_igar.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/InteractivePreview-XDSzQLOY.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/index-D-zYbzFZ.js"],css:["/assets/InteractivePreview-CMKNK2uU.css"],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-C3FZJx1w.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/InteractivePreview-XDSzQLOY.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/index-D-zYbzFZ.js"],css:["/assets/InteractivePreview-CMKNK2uU.css"],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-CxvZPkCv.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/settings-5zF_GOcS.js","/assets/file-text-LM0mgxXE.js","/assets/LogViewer-CRcT5fOZ.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/ScenarioPreview-Bi-YUMa-.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/chart-column-B8fb6wnw.js","/assets/circle-alert-IdsgAK39.js","/assets/SafeScreenshot-Bual6h18.js","/assets/LibraryFunctionPreview-BYVx9KFp.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-8Els_3Wb.js",imports:["/assets/ReportIssueModal-BORLgi0X.js","/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/InteractivePreview-XDSzQLOY.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/ScenarioPreview-Bi-YUMa-.js","/assets/ScenarioViewer-4D2vLLJz.js","/assets/SafeScreenshot-Bual6h18.js","/assets/EntityTypeIcon-D5ZHFomX.js","/assets/LogViewer-CRcT5fOZ.js","/assets/loader-circle-BXPKbHEb.js","/assets/settings-5zF_GOcS.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/circle-check-BACUUf75.js","/assets/triangle-alert-D7k-ArFa.js","/assets/index-D-zYbzFZ.js","/assets/LibraryFunctionPreview-BYVx9KFp.js","/assets/circle-alert-IdsgAK39.js","/assets/file-text-LM0mgxXE.js","/assets/chart-column-B8fb6wnw.js"],css:["/assets/InteractivePreview-CMKNK2uU.css"],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-BQ-02-jB.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/SafeScreenshot-Bual6h18.js","/assets/entityStatus-BEqj2qBy.js","/assets/EntityTypeIcon-D5ZHFomX.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/clock-vWeoCemX.js","/assets/file-text-LM0mgxXE.js","/assets/chart-column-B8fb6wnw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-DIOEw_3i.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/ScenarioViewer-4D2vLLJz.js","/assets/InteractivePreview-XDSzQLOY.js","/assets/LogViewer-CRcT5fOZ.js","/assets/SafeScreenshot-Bual6h18.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/ReportIssueModal-BORLgi0X.js","/assets/settings-5zF_GOcS.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/circle-check-BACUUf75.js","/assets/triangle-alert-D7k-ArFa.js","/assets/index-D-zYbzFZ.js"],css:["/assets/InteractivePreview-CMKNK2uU.css"],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-Dc4MlMpK.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-BC200mfN.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/useToast-Ddo4UQv7.js","/assets/LogViewer-CRcT5fOZ.js","/assets/EntityTypeIcon-D5ZHFomX.js","/assets/SafeScreenshot-Bual6h18.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/circle-check-BACUUf75.js","/assets/settings-5zF_GOcS.js","/assets/zap-_jw-9DCp.js","/assets/loader-circle-BXPKbHEb.js","/assets/file-text-LM0mgxXE.js","/assets/chart-column-B8fb6wnw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/files-Dxh9CcaV.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/EntityTypeIcon-D5ZHFomX.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/LibraryFunctionPreview-BYVx9KFp.js","/assets/SafeScreenshot-Bual6h18.js","/assets/entityStatus-BEqj2qBy.js","/assets/triangle-alert-D7k-ArFa.js","/assets/file-text-LM0mgxXE.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/chart-column-B8fb6wnw.js","/assets/clock-vWeoCemX.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/git-BXmqrWCH.js",imports:["/assets/chunk-WWGJGFF6-De6i8FUT.js","/assets/useLastLogLine-AlhS7g5F.js","/assets/useToast-Ddo4UQv7.js","/assets/LogViewer-CRcT5fOZ.js","/assets/EntityTypeIcon-D5ZHFomX.js","/assets/entityVersioning-Bk_YB1jM.js","/assets/createLucideIcon-CS7XDrKv.js","/assets/zap-_jw-9DCp.js","/assets/circle-alert-IdsgAK39.js","/assets/circle-check-BACUUf75.js","/assets/SafeScreenshot-Bual6h18.js","/assets/file-text-LM0mgxXE.js","/assets/chart-column-B8fb6wnw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-1af162d4.js",version:"1af162d4",sri:void 0},Gm="build/client",Hm="/",Km={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Vm=!0,Jm=!1,Qm=[],Zm={mode:"lazy",manifestPath:"/__manifest"},Xm="/",eh={module:$s},th={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:ii},"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:Mi},"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:ji},"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:Sl},"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:_l},"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:Gl},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Kl},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Rc},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Dc},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Fc},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Bc},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:qc},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Zc},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:nd},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:ad},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:od},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:ld},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:xd},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:wd},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Nd},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Gd},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Vd},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:su},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:iu},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:mu},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:fu},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:xu},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Au},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:_u},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:ju},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Yu},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:nm}};export{Yo as A,Oo as B,ce as C,ho as D,po as E,Ze as F,eo as G,Wr as H,ro as I,Gr as J,oo as K,lo as L,Gm as M,Hm as N,Km as O,Zs as P,Vm as Q,Jm as R,Un as S,Qm as T,Zm as U,Xm as V,eh as W,th as X,Wm as Y,Hs as a,it as b,Qe as c,Fe as d,Et as e,Yn as f,zn as g,qr as h,Ws as i,wo as j,Co as k,Nt as l,qe as m,Vr as n,ko as o,Qt as p,lt as q,Jr as r,Qr as s,$o as t,at as u,Zr as v,Pt as w,Do as x,ir as y,Bo as z};